Класс File
Класс File
Имя файла
Путь к файлу и имя файла
Имя файла
Класс File
Создание файла
Создание файла
Переименование файла
Переименование файла
Удаление файла
Удаление файла
Запрашивание атрибутов
Запрашивание атрибутов
Запрашивание времени последнего изменения
Запрашивание времени последнего изменения
Изменение свойств
Изменение атрибутов
Изменение атрибутов
Изменение времени последней модификации
Изменение времени последней модификации
Работа с директориями
Получение списка файлов и директорий
Получение списка файлов и директорий
Создание директорий
Создание директорий
1.04M
Категория: ПрограммированиеПрограммирование

Ввод - вывод. Файлы

1.

2.

V. Ввод - вывод
1. Файлы
2

3. Класс File

3

4. Класс File

package
package java.io;
java.io;
public
public class
class File
File {{
private
private String
String path;
path;
static
private
FileSystem
static private FileSystem fs
fs == FileSystem.getFileSystem();
FileSystem.getFileSystem();
public
public File(String
File(String pathname)
pathname) {{
if
if (pathname
(pathname ==
== null)
null) {{
throw
throw new
new NullPointerException();
NullPointerException();
}}
this.path
this.path == fs.normalize(pathname);
fs.normalize(pathname);
this.prefixLength
this.prefixLength == fs.prefixLength(this.path);
fs.prefixLength(this.path);
}}
public
public File(String
File(String parent,
parent, String
String child)
child)
public
public File(File
File(File parent,
parent, String
String child)
child)
public
public boolean
boolean exists()
exists()
public
public String
String getPath()
getPath() {{
return
return path;
path;
}}
}}
...
...
C
Класс File из пакета java.io представляет путь к директории или файлу и содержит
методы для получения информации о файловой системе и внесения изменений в
файловую систему. Конструкторы позволяют задавать путь к файлу или директории.
Директория или файл чей путь хранится в File может не существовать.
4

5. Имя файла

public
public class
class FileNameDemo
FileNameDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
}}
}}
File
File file
file == new
new File("Hello
File("Hello World!");
World!");
System.out.println("File
\""+
System.out.println("File \""+ file.getPath()
file.getPath() +"\"
+"\" exists?
exists? "" ++ file.exists());
file.exists());
File
File "Hello
"Hello World!"
World!" exists?
exists? false
false
5

6.

Получение информации
о пути к файлу и об имени файла
6

7. Путь к файлу и имя файла

public
public class
class File
File {{
...
...
public
public String
String getName()
getName()
public
public File
File getParentFile()
getParentFile()
public
String
public String getParent()
getParent()
public
public File
File getAbsoluteFile()
getAbsoluteFile()
public
public String
String getAbsolutePath()
getAbsolutePath()
}}
C
Используя методы класса File можно
запросить информацию об имени файла
или директории и о пути к файлу или
директории.
7

8. Имя файла

public
public class
class PathInfoDemo
PathInfoDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
File
File file
file == new
new File("I:\\FileIO\\somefile.txt");
File("I:\\FileIO\\somefile.txt");
System.out.println("File
System.out.println("File
System.out.println("File
System.out.println("File
System.out.println("File
System.out.println("File
}}
name:
name: "" ++ file.getName());
file.getName());
directory:
directory: "" ++ file.getParent());
file.getParent());
full
full path:
path: "" ++ file.getAbsolutePath());
file.getAbsolutePath());
}}
File
File name:
name: somefile.txt
somefile.txt
File
File directory:
directory: I:\FileIO
I:\FileIO
File
File full
full path:
path: I:\FileIO\somefile.txt
I:\FileIO\somefile.txt
8

9.

Создание, удаление и переименование файлов
9

10. Класс File

package
package java.io;
java.io;
public
public class
class File
File {{
}}
...
...
public
public
public
public
public
public
boolean
boolean
boolean
boolean
boolean
boolean
C
createNewFile()
createNewFile()
delete()
delete()
renameTo(File
renameTo(File dest)
dest)
Создать новый файл можно с помощью метода createNewFile. Попытка создать файл в
несуществующей директории приведёт к выбрасыванию исключения IOException. Удалить
файл можно вызвав метод delete. Если файл успешно удалён delete вернёт true если
удаляемый файл не существует delete вернёт false. Переименовать файл можно с помощью
метода renameTo. В случае успешного переименования он вернёт true в случае если
переименуемый файл не существует renameTo вернёт false.
10

11. Создание файла

public
public class
class CreateFileDemo
CreateFileDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
try
try {{
File
File file
file == new
new File("I:\\FileIO\\somefile.txt");
File("I:\\FileIO\\somefile.txt");
if
if (file.createNewFile())
(file.createNewFile()) {{
System.out.println("File
System.out.println("File "" ++ file.getName()
file.getName() ++ "" was
was created");
created");
}} else
{
else {
System.out.println("Create
System.out.println("Create operation
operation failed.");
failed.");
}}
}} catch
catch (IOException
(IOException e)
e) {{
}}
}}
}}
e.printStackTrace();
e.printStackTrace();
Обычно файлы не создаются явно
с помощью createNewFile. Они
создаются при помощи классов
потомков OutputStream или Writer.
11

12. Создание файла

File
File somefile.txt
somefile.txt was
was created
created
12

13. Переименование файла

public
public class
class RenameFileDemo
RenameFileDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
File
File oldfile
oldfile == new
new File("I:\\FileIO\\somefile.txt");
File("I:\\FileIO\\somefile.txt");
File
File newfile
newfile == new
new File("I:\\FileIO\\newfile.txt");
File("I:\\FileIO\\newfile.txt");
if
if (oldfile.renameTo(newfile))
(oldfile.renameTo(newfile)) {{
System.out.println("Rename
System.out.println("Rename succesful
succesful "" ++ oldfile.getName()
oldfile.getName() ++ "" was
was renamed
renamed to
to "" ++
newfile.getName());
newfile.getName());
}} else
else {{
System.out.println("Rename
System.out.println("Rename failed");
failed");
}}
}}
}}
13

14. Переименование файла

Rename
Rename succesful
succesful somefile.txt
somefile.txt was
was renamed
renamed to
to newfile.txt
newfile.txt
14

15. Удаление файла

public
public class
class DeleteFileDemo
DeleteFileDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
File
File file
file == new
new File("I:\\FileIO\\somefile.txt");
File("I:\\FileIO\\somefile.txt");
}}
}}
if
if (file.delete())
(file.delete()) {{
System.out.println(file.getName()
System.out.println(file.getName() ++ "" was
was deleted!");
deleted!");
}} else
else {{
System.out.println("Delete
System.out.println("Delete operation
operation failed.");
failed.");
}}
15

16. Удаление файла

newfile.txt
newfile.txt was
was deleted!
deleted!
16

17.

Запрашивание свойств
17

18.

package
package java.io;
java.io;
public
public class
class File
File {{
...
...
public
public boolean
boolean isDirectory()
isDirectory()
public
public boolean
boolean isFile()
isFile()
public
public
public
public
public
public
public
public
}}
boolean
boolean
boolean
boolean
boolean
boolean
boolean
boolean
isHidden()
isHidden()
canRead
canRead ()
()
canWrite
canWrite ()
()
canExecute
canExecute ()
()
public
public long
long lastModified()
lastModified()
public
public long
long length()
length()
C
Получить информацию о том является ли файл спрятанным и
изменяемым можно с помощью методов isHidden и canWrite
соответственно. Время последней модификации можно узнать
с помощью метода lastModified. Длину файла можно узнать с
помощью метода length.
18

19. Запрашивание атрибутов

public
public class
class ListAttributesDemo
ListAttributesDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
File
File file
file == new
new File("I:\\FileIO\\somefile.txt");
File("I:\\FileIO\\somefile.txt");
if
if (file.isHidden())
(file.isHidden()) {{
System.out.println("This
System.out.println("This file
file is
is hidden");
hidden");
}} else
else {{
System.out.println("This
System.out.println("This file
file is
is not
not hidden");
hidden");
}}
if
if (file.canRead())
(file.canRead()) {{
System.out.println("This
System.out.println("This file
file is
is readable");
readable");
}} else
else {{
System.out.println("This
System.out.println("This file
file is
is not
not readable");
readable");
}}
if
if (file.canWrite())
(file.canWrite()) {{
System.out.println("This
System.out.println("This file
file is
is writable");
writable");
}} else
else {{
System.out.println("This
System.out.println("This file
file is
is not
not writable");
writable");
}}
}}
}}
if
if (file.canExecute())
(file.canExecute()) {{
System.out.println("This
System.out.println("This file
file is
is executable");
executable");
}} else
else {{
System.out.println("This
System.out.println("This file
file is
is not
not executable");
executable");
}}
19

20. Запрашивание атрибутов

This
This
This
This
This
This
This
This
file
file
file
file
file
file
file
file
is
is
is
is
is
is
is
is
hidden
hidden
readable
readable
not
not writable
writable
executable
executable
20

21. Запрашивание времени последнего изменения

public
public class
class TimeDemo
TimeDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
File
File file
file == new
new File("F:\\FileIO\\somefile.txt");
File("F:\\FileIO\\somefile.txt");
System.out.println("Before
System.out.println("Before Format
Format :: "" ++ file.lastModified());
file.lastModified());
SimpleDateFormat
SimpleDateFormat sdf
sdf == new
new SimpleDateFormat("MM/dd/yyyy
SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
HH:mm:ss");
}}
}}
System.out.println("After
System.out.println("After Format
Format :: "" ++ sdf.format(file.lastModified()));
sdf.format(file.lastModified()));
21

22. Запрашивание времени последнего изменения

Before
Before Format
Format :: 1354014410437
1354014410437
After
Format
:
11/27/2012
After Format : 11/27/2012 18:06:50
18:06:50
22

23.

Изменение свойств
23

24. Изменение свойств

public
public class
class File
File {{
...
...
public
public
public
public
public
public
boolean
boolean
boolean
boolean
boolean
boolean
setReadOnly()
setReadOnly()
setWritable(boolean
setWritable(boolean writable)
writable)
setExecutable(boolean
setExecutable(boolean executable)
executable)
public
public boolean
boolean setLastModified(long
setLastModified(long time)
time)
}}
C
Файл можно сделать изменяемым или неизменяемым с
помощью методов setReadOnly и setWritable. Время
последней модификации можно задать с помощью
setLastModified. Сделать файл спрятанным или не
спрятанным нельзя.
24

25. Изменение атрибутов

public
public class
class SetAttributesDemo
SetAttributesDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
File
File file
file == new
new File("I:\\FileIO\\somefile.txt");
File("I:\\FileIO\\somefile.txt");
file.setWritable(false);
file.setWritable(false);
//file.setReadOnly();
//file.setReadOnly();
if
if (file.canRead())
(file.canRead()) {{
System.out.println("This
System.out.println("This file
file is
is readable");
readable");
}} else
else {{
System.out.println("This
System.out.println("This file
file is
is not
not readable");
readable");
}}
}}
}}
if
if (file.canWrite())
(file.canWrite()) {{
System.out.println("This
System.out.println("This file
file is
is writable");
writable");
}} else
else {{
System.out.println("This
System.out.println("This file
file is
is not
not writable");
writable");
}}
25

26. Изменение атрибутов

This
This
This
This
file
file
file
file
is
is
is
is
readable
readable
not
not writable
writable
26

27. Изменение времени последней модификации

public
public class
class SetTimeDemo
SetTimeDemo {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
File
File file
file == new
new File("I:\\FileIO\\somefile.txt");
File("I:\\FileIO\\somefile.txt");
SimpleDateFormat
SimpleDateFormat sdf
sdf == new
new SimpleDateFormat("MM/dd/yyyy
SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
HH:mm:ss");
System.out.println("Last
System.out.println("Last modified
modified :: "" ++ sdf.format(file.lastModified()));
sdf.format(file.lastModified()));
long
long mils
mils == file.lastModified();
file.lastModified();
mils
mils +=
+= 1000L
1000L ** 60
60 ** 60
60 ** 24
24 ** 365;
365;
}}
}}
if
if (file.setLastModified(mils))
(file.setLastModified(mils)) {{
System.out.println("File
System.out.println("File "" ++ file.getName()
file.getName()
++ "" last
modified
time
was
last modified time was changed");
changed");
}} else
else {{
System.out.println("Last
System.out.println("Last modified
modified change
change operation
operation failed.");
failed.");
}}
System.out.println("Last
System.out.println("Last modified
modified :: "" ++ sdf.format(file.lastModified()));
sdf.format(file.lastModified()));
27

28. Изменение времени последней модификации

Last
Last
File
File
Last
Last
modified
modified :: 12/20/2015
12/20/2015 11:43:20
11:43:20
somefile.txt
last
modified
somefile.txt last modified time
time was
was changed
changed
modified
modified :: 12/19/2016
12/19/2016 11:43:20
11:43:20
28

29.

Работа с директориями
29

30. Работа с директориями

public
public class
class File
File {{
}}
...
...
public
public
public
public
public
public
public
public
public
public
public
public
boolean
boolean mkdir()
mkdir()
boolean
mkdirs()
boolean mkdirs()
boolean
boolean isDirectory()
isDirectory()
File[]
File[] listFiles()
listFiles()
boolean
boolean delete()
delete()
boolean
renameTo(File
boolean renameTo(File dest)
dest)
C
Директорию можно создать с помощью метода mkdir. Несколько
вложенных директорий можно создать с помощью метода
mkdirs. Получить список файлов и директорий можно с
помощью метода listFiles. Удаление и переименование
директорий возможно с помощью методов delete и renameTo.
30

31. Получение списка файлов и директорий

public
public class
class ListDirDemo
ListDirDemo {{
public
public static
static void
void main(String
main(String args[])
args[]) {{
String
String dirname
dirname == "F:\\eclipse";
"F:\\eclipse";
File
File file
file == new
new File(dirname);
File(dirname);
if
if (file.isDirectory())
(file.isDirectory()) {{
System.out.println("Directory
System.out.println("Directory of
of "" ++ dirname);
dirname);
File[]
files
=
file.listFiles();
File[] files = file.listFiles();
for
for (int
(int ii == 0;
0; ii << files.length;
files.length; i++)
i++) {{
if
if (files[i].isDirectory())
(files[i].isDirectory()) {{
System.out.println(files[i].getAbsolutePath()
System.out.println(files[i].getAbsolutePath()
++ "" is
is aa directory");
directory");
}} else
else {{
System.out.print(files[i]
System.out.print(files[i] ++ "" is
is aa file
file ");
");
System.out.println("
System.out.println(" is
is hidden?
hidden? :: "" ++ files[i].isHidden());
files[i].isHidden());
}}
}}
}}
}}
}} else
else {{
System.out.println(dirname
System.out.println(dirname ++ "" is
is not
not aa directory");
directory");
}}
31

32. Получение списка файлов и директорий

Directory
Directory of
of F:\eclipse
F:\eclipse
F:\eclipse\.eclipseproduct
F:\eclipse\.eclipseproduct is
is aa file
file is
is hidden?
hidden? :: false
false
F:\eclipse\artifacts.xml
F:\eclipse\artifacts.xml is
is aa file
file is
is hidden?
hidden? :: false
false
F:\eclipse\configuration
F:\eclipse\configuration is
is aa directory
directory
F:\eclipse\dropins
F:\eclipse\dropins is
is aa directory
directory
F:\eclipse\eclipse.exe
F:\eclipse\eclipse.exe is
is aa file
file is
is hidden?
hidden? :: false
false
F:\eclipse\eclipse.ini
is
a
file
is
hidden?
:
false
F:\eclipse\eclipse.ini is a file is hidden? : false
F:\eclipse\eclipsec.exe
F:\eclipse\eclipsec.exe is
is aa file
file is
is hidden?
hidden? :: false
false
F:\eclipse\epl-v10.html
F:\eclipse\epl-v10.html is
is aa file
file is
is hidden?
hidden? :: false
false
F:\eclipse\features
F:\eclipse\features is
is aa directory
directory
F:\eclipse\hs_err_pid3840.log
F:\eclipse\hs_err_pid3840.log is
is aa file
file is
is hidden?
hidden? :: false
false
F:\eclipse\notice.html
is
a
file
is
hidden?
:
false
F:\eclipse\notice.html is a file is hidden? : false
F:\eclipse\p2
F:\eclipse\p2 is
is aa directory
directory
F:\eclipse\plugins
F:\eclipse\plugins is
is aa directory
directory
F:\eclipse\readme
F:\eclipse\readme is
is aa directory
directory
32

33. Создание директорий

public
public class
class CreateDirDemo
CreateDirDemo {{
public
public static
static void
void main(String
main(String args[])
args[]) {{
String
String dirname
dirname == "I:\\FileIO";
"I:\\FileIO";
File
File dir
dir == new
new File(dirname);
File(dirname);
if
if (dir.exists())
(dir.exists()) {{
System.out.println("Directory
System.out.println("Directory of
of "" ++ dirname
dirname +"
+" exists");
exists");
}}
else
else {{
System.out.println("Directory
System.out.println("Directory of
of "" ++ dirname
dirname +"
+" does
does not
not exist");
exist");
}}
}}
}}
if
if (dir.mkdir())
(dir.mkdir()) {{
System.out.println("Directory
System.out.println("Directory "" ++ dir.getName()
dir.getName() ++ "" was
was created");
created");
}} else
else {{
System.out.println("Create
System.out.println("Create operation
operation failed.");
failed.");
}}
33

34. Создание директорий

Directory
Directory of
of I:\FileIO
I:\FileIO does
does not
not exist
exist
Directory
Directory FileIO
FileIO was
was created
created
34
English     Русский Правила