Как создать файл в java
Перейти к содержимому

Как создать файл в java

  • автор:

Reading, Writing, and Creating Files

This page discusses the details of reading, writing, creating, and opening files. There are a wide array of file I/O methods to choose from. To help make sense of the API, the following diagram arranges the file I/O methods by complexity.

File I/O Methods Arranged from Less Complex to More Complex

On the far left of the diagram are the utility methods readAllBytes , readAllLines , and the write methods, designed for simple, common cases. To the right of those are the methods used to iterate over a stream or lines of text, such as newBufferedReader , newBufferedWriter , then newInputStream and newOutputStream . These methods are interoperable with the java.io package. To the right of those are the methods for dealing with ByteChannels , SeekableByteChannels , and ByteBuffers , such as the newByteChannel method. Finally, on the far right are the methods that use FileChannel for advanced applications needing file locking or memory-mapped I/O.

This page has the following topics:

The OpenOptions Parameter

Several of the methods in this section take an optional OpenOptions parameter. This parameter is optional and the API tells you what the default behavior is for the method when none is specified.

The following StandardOpenOptions enums are supported:

  • WRITE – Opens the file for write access.
  • APPEND – Appends the new data to the end of the file. This option is used with the WRITE or CREATE options.
  • TRUNCATE_EXISTING – Truncates the file to zero bytes. This option is used with the WRITE option.
  • CREATE_NEW – Creates a new file and throws an exception if the file already exists.
  • CREATE – Opens the file if it exists or creates a new file if it does not.
  • DELETE_ON_CLOSE – Deletes the file when the stream is closed. This option is useful for temporary files.
  • SPARSE – Hints that a newly created file will be sparse. This advanced option is honored on some file systems, such as NTFS, where large files with data "gaps" can be stored in a more efficient manner where those empty gaps do not consume disk space.
  • SYNC – Keeps the file (both content and metadata) synchronized with the underlying storage device.
  • DSYNC – Keeps the file content synchronized with the underlying storage device.

Commonly Used Methods for Small Files

Reading All Bytes or Lines from a File

If you have a small-ish file and you would like to read its entire contents in one pass, you can use the readAllBytes(Path) or readAllLines(Path, Charset) method. These methods take care of most of the work for you, such as opening and closing the stream, but are not intended for handling large files. The following code shows how to use the readAllBytes method:

Writing All Bytes or Lines to a File

You can use one of the write methods to write bytes, or lines, to a file.

  • write(Path, byte[], OpenOption. )
  • write(Path, Iterable< extends CharSequence>, Charset, OpenOption. )

The following code snippet shows how to use a write method.

Buffered I/O Methods for Text Files

The java.nio.file package supports channel I/O, which moves data in buffers, bypassing some of the layers that can bottleneck stream I/O.

Reading a File by Using Buffered Stream I/O

The newBufferedReader(Path, Charset) method opens a file for reading, returning a BufferedReader that can be used to read text from a file in an efficient manner.

The following code snippet shows how to use the newBufferedReader method to read from a file. The file is encoded in "US-ASCII."

Writing a File by Using Buffered Stream I/O

You can use the newBufferedWriter(Path, Charset, OpenOption. ) method to write to a file using a BufferedWriter .

The following code snippet shows how to create a file encoded in "US-ASCII" using this method:

Methods for Unbuffered Streams and Interoperable with java.io APIs

Reading a File by Using Stream I/O

To open a file for reading, you can use the newInputStream(Path, OpenOption. ) method. This method returns an unbuffered input stream for reading bytes from the file.

Creating and Writing a File by Using Stream I/O

You can create a file, append to a file, or write to a file by using the newOutputStream(Path, OpenOption. ) method. This method opens or creates a file for writing bytes and returns an unbuffered output stream.

The method takes an optional OpenOption parameter. If no open options are specified, and the file does not exist, a new file is created. If the file exists, it is truncated. This option is equivalent to invoking the method with the CREATE and TRUNCATE_EXISTING options.

The following example opens a log file. If the file does not exist, it is created. If the file exists, it is opened for appending.

Methods for Channels and ByteBuffers

Reading and Writing Files by Using Channel I/O

While stream I/O reads a character at a time, channel I/O reads a buffer at a time. The ByteChannel interface provides basic read and write functionality. A SeekableByteChannel is a ByteChannel that has the capability to maintain a position in the channel and to change that position. A SeekableByteChannel also supports truncating the file associated with the channel and querying the file for its size.

The capability to move to different points in the file and then read from or write to that location makes random access of a file possible. See Random Access Files for more information.

There are two methods for reading and writing channel I/O.

  • newByteChannel(Path, OpenOption. )
  • newByteChannel(Path, Set<? extends OpenOption>, FileAttribute<?>. )

Both newByteChannel methods enable you to specify a list of OpenOption options. The same open options used by the newOutputStream methods are supported, in addition to one more option: READ is required because the SeekableByteChannel supports both reading and writing.

Specifying READ opens the channel for reading. Specifying WRITE or APPEND opens the channel for writing. If none of these options are specified, then the channel is opened for reading.

The following code snippet reads a file and prints it to standard output:

The following example, written for UNIX and other POSIX file systems, creates a log file with a specific set of file permissions. This code creates a log file or appends to the log file if it already exists. The log file is created with read/write permissions for owner and read only permissions for group.

Methods for Creating Regular and Temporary Files

Creating Files

You can create an empty file with an initial set of attributes by using the createFile(Path, FileAttribute<?>) method. For example, if, at the time of creation, you want a file to have a particular set of file permissions, use the createFile method to do so. If you do not specify any attributes, the file is created with default attributes. If the file already exists, createFile throws an exception.

In a single atomic operation, the createFile method checks for the existence of the file and creates that file with the specified attributes, which makes the process more secure against malicious code.

The following code snippet creates a file with default attributes:

POSIX File Permissions has an example that uses createFile(Path, FileAttribute<?>) to create a file with pre-set permissions.

You can also create a new file by using the newOutputStream methods, as described in Creating and Writing a File using Stream I/O. If you open a new output stream and close it immediately, an empty file is created.

Creating Temporary Files

You can create a temporary file using one of the following createTempFile methods:

  • createTempFile(Path, String, String, FileAttribute<?>)
  • createTempFile(String, String, FileAttribute<?>)

The first method allows the code to specify a directory for the temporary file and the second method creates a new file in the default temporary-file directory. Both methods allow you to specify a suffix for the filename and the first method allows you to also specify a prefix. The following code snippet gives an example of the second method:

Java Files

OOPS oriented Java Programming Language

File handling is an important part of any application.

Java has several methods for creating, reading, updating, and deleting files.

Java File Handling

The File class from the java.io package, allows us to work with files.

To use the File class, create an object of the class, and specify the filename or directory name:

Example

Java Create and Write To Files

Create a File

To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that the method is enclosed in a try. catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some reason):

Example

The output will be:

To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the “ \ " character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt

Example

Write To a File

In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you are done writing to the file, you should close it with the close() method:

Example

The output will be:

Read a File

In the following example, we use the Scanner class to read the contents of the text file we created.

Example

The output will be:

Example

The output will be:

Note: There are many available classes in the Java API that can be used to read and write files in Java: FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStream , etc. Which one to use depends on the Java version you're working with and whether you need to read bytes or characters, and the size of the file/lines etc.

Как создать файл в java

Класс File, определенный в пакете java.io, не работает напрямую с потоками. Его задачей является управление информацией о файлах и каталогах. Хотя на уровне операционной системы файлы и каталоги отличаются, но в Java они описываются одним классом File.

В зависимости от того, что должен представлять объект File — файл или каталог, мы можем использовать один из конструкторов для создания объекта:

Класс File имеет ряд методов, которые позволяют управлять файлами и каталогами. Рассмотрим некоторые из них:

boolean createNewFile() : создает новый файл по пути, который передан в конструктор. В случае удачного создания возвращает true, иначе false

boolean delete() : удаляет каталог или файл по пути, который передан в конструктор. При удачном удалении возвращает true.

boolean exists() : проверяет, существует ли по указанному в конструкторе пути файл или каталог. И если файл или каталог существует, то возвращает true, иначе возвращает false

String getAbsolutePath() : возвращает абсолютный путь для пути, переданного в конструктор объекта

String getName() : возвращает краткое имя файла или каталога

String getParent() : возвращает имя родительского каталога

boolean isDirectory() : возвращает значение true, если по указанному пути располагается каталог

boolean isFile() : возвращает значение true, если по указанному пути находится файл

boolean isHidden() : возвращает значение true, если каталог или файл являются скрытыми

long length() : возвращает размер файла в байтах

long lastModified() : возвращает время последнего изменения файла или каталога. Значение представляет количество миллисекунд, прошедших с начала эпохи Unix

String[] list() : возвращает массив файлов и подкаталогов, которые находятся в определенном каталоге

File[] listFiles() : возвращает массив файлов и подкаталогов, которые находятся в определенном каталоге

boolean mkdir() : создает новый каталог и при удачном создании возвращает значение true

boolean renameTo(File dest) : переименовывает файл или каталог

Работа с каталогами

Если объект File представляет каталог, то его метод isDirectory() возвращает true . И поэтому мы можем получить его содержимое — вложенные подкаталоги и файлы с помощью методов list() и listFiles() . Получим все подкаталоги и файлы в определенном каталоге:

Теперь выполним еще ряд операций с каталогами, как удаление, переименование и создание:

Работа с файлами

Работа с файлами аналогична работе с каталога. Например, получим данные по одному из файлов и создадим еще один файл:

При создании нового файла метод createNewFile() в случае неудачи выбрасывает исключение IOException , поэтому нам надо его отлавливать, например, в блоке try. catch, как делается в примере выше.

Как создать файл в Java?

Обработка файлов в Java необходима для выполнения различных задач, таких как создание, чтение, запись и т. д. В этой статье я расскажу вам, как создать файл в Java с использованием различных методов.

Одна из главных причин популярности Java – независимость от платформы. Java по-прежнему является актуальным языком программирования, который не имеет признаков снижения популярности, и поэтому его стоит изучать. Большинство разработчиков выбирают его как свой первый язык программирования, потому что его легко выучить.

Поток выполнения Java-программы

Выполнение программы Java

Все языки программирования высокого уровня (также называемые третьим поколением) позволяют писать программы на языке, аналогичном (хотя и гораздо более простом), чем естественный язык. Программа высокого уровня называется исходным кодом.

Что такое файл в Java?

Файл – это не что иное, как простое хранилище данных на языке Java. Файловая система может реализовывать ограничения для определенных операций, таких как чтение, запись и выполнение. Эти ограничения известны как права доступа.

При чтении файла в Java мы должны знать класс файлов Java. Класс Java File представляет файлы и имена каталогов в абстрактной манере. Класс File имеет несколько методов для работы с каталогами и файлами, таких как создание новых каталогов или файлов, удаление и переименование каталогов или файлов и т. д. Объект File представляет фактический файл / каталог на диске.

Теперь давайте разберемся с различными методами создания файла.

Методы для создания файла в Java

1. Создайте файл с классом java.io.File

Вам нужно использовать метод File.createNewFile(). Этот метод возвращает логическое значение:

  • истина, если файл выполнен.
  • false, если файл уже существует или операция по какой-то причине не открывается.

Этот метод также генерирует исключение java.io.IOException, когда он не может создать файл.

Когда мы создаем объект File, передавая имя файла, он может быть с абсолютным путем, или мы можем предоставить только имя файла, или мы можем предоставить относительный путь. Для неабсолютного пути объект File пытается найти файлы в корневом каталоге проекта.

Если мы запустим программу из командной строки, для неабсолютного пути объект File попытается найти файлы из текущего каталога. Экземпляры класса File являются неизменяемыми; то есть, после создания абстрактный путь, представленный объектом File, никогда не изменится.

Теперь давайте рассмотрим небольшой пример и разберемся, как он работает.

Пожалуйста, обратите внимание, что этот метод будет только создавать файл, но не записывать в него никакого содержимого. Теперь давайте двигаться дальше и рассмотрим следующий метод.

2. Создайте файл с классом java.io.FileOutputStream

Если вы хотите создать новый файл и в то же время, если хотите записать в него некоторые данные, вы можете использовать метод записи FileOutputStream. В Java FileOutputStream является классом потока байтов. Чтобы записать данные в файл, вы должны преобразовать данные в байты, а затем сохранить их в файл.

Класс FileOutputStream хранит данные в виде отдельных байтов. Может использоваться для создания текстовых файлов. Файл представляет собой хранилище данных на втором носителе, таком как жесткий диск или компакт-диск. Метод FileOutputStream.write() автоматически создает новый файл и записывает в него содержимое.

3. Создайте файл с помощью Java.nio.file.Files – Java NIO

Files.write() – лучший способ создать файл, и он должен быть вашим предпочтительным подходом в будущем, если вы его еще не используете. Это хороший вариант, потому что нам не нужно беспокоиться о закрытии ресурсов ввода-вывода. Каждая строка представляет собой последовательность символов и записывается в файл последовательно, каждая строка заканчивается разделителем строк платформы.

public static Path createFile(Path path, FileAttribute<?>. attrs) throws IOException

Создает новый и пустой файл, и если файл уже существует, то будет ошибка.

путь – путь для создания файла.

attrs – необязательный список атрибутов файла, устанавливаемых атомарно при создании.

Далее, давайте посмотрим на создание временного файла.

4. Java также может создавать временные файлы

Создание временного файла в java может потребоваться во многих сценариях, но в основном это происходит во время модульных тестов, где вы не хотите сохранять результаты. Как только тестовый пример закончен, вас не волнует содержимое файла.

Создание временного файла с использованием java.io.File.createTempFile()

с использованием NIO

Для создания временного файла используются следующие два метода.

1. createTempFile(Path, String, String, FileAttribute<?>… attrs) – создает файл tmp в указанном каталоге.

Вышеуказанный метод принимает четыре аргумента.

Путь -> указать каталог, в котором будет создан файл.

Строка -> чтобы упомянуть префикс имени файла. Используйте ноль, чтобы избежать префикса.

Строка -> чтобы упомянуть суффикс имени файла. т.е. расширение файла. Используйте null, чтобы использовать .tmp в качестве расширения.

attrs -> Это необязательно, чтобы упоминать список атрибутов файла, чтобы установить атомарно при создании файла

Например. Files.createTempFile(path,null, null); – создает временный файл с расширением .tmp по указанному пути

2. createTempFile(String, String, FileAttribute<?>) – создает временный файл во временном каталоге по умолчанию системы / сервера.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *