Java -файлы
Работа с файлами является важной частью любого приложения.
В Java есть несколько методов для создания, чтения, обновления и удаления файлов.
Обработка файлов Java
Класс File
из java.io
пакета, позволяет нам работать с файлами.
Чтобы использовать File
класс, создайте объект класса и укажите имя файла или каталога:
Пример
import java.io.File; // Import the File class
File myObj = new File("filename.txt"); // Specify the filename
Если вы не знаете, что такое пакет, прочитайте наш учебник по пакетам Java .
Класс File
имеет множество полезных методов для создания и получения информации о файлах. Например:
Method | Type | Description |
---|---|---|
canRead() |
Boolean | Tests whether the file is readable or not |
canWrite() |
Boolean | Tests whether the file is writable or not |
createNewFile() |
Boolean | Creates an empty file |
delete() |
Boolean | Deletes a file |
exists() |
Boolean | Tests whether the file exists |
getName() |
String | Returns the name of the file |
getAbsolutePath() |
String | Returns the absolute pathname of the file |
length() |
Long | Returns the size of the file in bytes |
list() |
String[] | Returns an array of the files in the directory |
mkdir() |
Boolean | Creates a directory |
Вы узнаете, как создавать, записывать, читать и удалять файлы в следующих главах: