Creating text file with java

Creating a New File in Java

Learn to create a new file using different techniques including NIO Path, IO File, OutputStream, and open-source libraries such as Guava and Apache commons.

1. Create New File using Java NIO

The Files.createFile(path, attribs) is the best way to create a new, empty and writable file in Java and it should be your preferred approach in the future if you are not already using it.

  • The createFile() method takes the Path interface instead of the File. It checks if the file already exists, and creates the file thereafter.
  • Checking any existing file and creating the file is done in a single atomic operation.
  • The attribs an optional list of file attributes to set atomically when creating the file.
  • It returns FileAlreadyExistsException If a file of that name already exists.
  • It returns IOException if an I/O error occurs or the parent directory does not exist.

Example 1: Create a new writable file

String TEXT_FILE = "C:/temp/io/textFile.txt"; Path textFilePath = Paths.get(TEXT_FILE); Files.createFile(textFilePath);

Example 2: Create a new read-only file

Set the file attributes while creating the file. In the given example, we are setting read-only (“ r “) access for the owner, group, and others using the string “r–r–r–“.

String TEXT_FILE = "C:/temp/io/textFile.txt"; Set permissions = PosixFilePermissions .fromString("r--r--r--"); FileAttribute attribs = PosixFilePermissions .asFileAttribute(permissions); Path textFilePath = Paths.get(TEXT_FILE); Files.createFile(textFilePath, attribs); 

2. Using File.createNewFile()

Use File.createNewFile() method to create a new file if and only if a file with this name does not yet exist. Checking any existing file and creating the file is an atomic operation.

This method returns a boolean value –

  • true if the file is created successfully.
  • false if the file already exists.
  • IOException If an I/O error occurred.
String TEXT_FILE = "C:/temp/io/textFile.txt"; File textFile = new File(TEXT_FILE); boolean isFileCreated = textFile.createNewFile(); 

The constructor automatically creates a new file in the given location. Note that if a file with a given name already exists, it will be overwritten.

It throws FileNotFoundException if the given file path represents a directory, or a new file cannot be created for any reason.

String TEXT_FILE = "C:/temp/io/textFile.txt"; try(FileOutputStream fos = new FileOutputStream(TEXT_FILE))< // We can write data as byte[] // fos.write(data, 0, data.length); >

To include Guava, add the following to pom.xml.

 com.google.guava guava 31.1-jre 

The Files.touch() method is similar to the Unix touch command. It creates an empty file or updates the last updated timestamp

The touch command, when used without any option, creates an empty file assuming the file doesn’t exist. If the file exists it changes the timestamp.

String TEXT_FILE = "C:/temp/io/textFile.txt"; com.google.common.io.Files.touch(new File(TEXT_FILE));

5. Apache Commons IO’s FileUtils

To include Apache Commons IO, add the following to pom.xml.

The FileUtils.touch() is very similar to the previous example. It also implements the same behavior as the “touch” utility on Unix.

Also, as from v1.3 this method creates parent directories if they do not exist. It throws an IOException if the last modified date of the file cannot be set.

String TEXT_FILE = "C:/temp/io/textFile.txt"; org.apache.commons.io.FileUtils.touch(new File(TEXT_FILE));

Источник

Как создать файл в 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, никогда не изменится.

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

File file = new File("c://temp//testFile1.txt"); //create the file. if (file.createNewFile()) < System.out.println("File is created!"); >else < System.out.println("File already exists."); >//write content FileWriter writer = new FileWriter (file); writer.write("Test data"); writer.close();

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

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

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

String data = "Test data"; FileOutputStream out = new FileOutputStream("c://temp//testFile2.txt"); out.write(data.getBytes()); out.close();

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

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

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

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

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

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

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

String data = "Test data"; Files.write(Paths.get("c://temp//testFile3.txt"); data.getBytes()); //or List lines = Arrays.asList("1st line", "2nd line"); Files.write(Paths.get("file6.txt"); lines, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND);

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

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

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

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

Public class TemporaryFileExample < Public static void main(string[] args)< try< final path path = Files.createTempFile("myTempFile",".txt"); System.out.println("Temp file : " + path); // delete file on exist. path.toFile().deleteonExit(); >catch (IOException e) < e.printStackTrace(); >> >
Public class TemporaryFileExample < Public static void main(string[] args)< File temp; try< temp = File.createTempFile("myTempFile" , ".txt"); System.out.println("Temp file created : " + temp.getAbsolutePath()); >catch (IOException e) < e.printStackTrace(); >> >

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

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

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

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

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

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

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

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

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

Например: Files.createTempFile (null, null) – создает временный файл во временной папке по умолчанию в системе. В Windows временная папка может быть C: UsersusernameAppDataLocalTemp, где username – ваш идентификатор входа в Windows.

Источник

Java Create and Write To Files

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

import java.io.File; // Import the File class import java.io.IOException; // Import the IOException class to handle errors public class CreateFile < public static void main(String[] args) < try < File myObj = new File("filename.txt"); if (myObj.createNewFile()) < System.out.println("File created: " + myObj.getName()); >else < System.out.println("File already exists."); >> catch (IOException e) < System.out.println("An error occurred."); e.printStackTrace(); >> > 

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

File myObj = new File("C:\\Users\\MyName\\filename.txt"); 

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

import java.io.FileWriter; // Import the FileWriter class import java.io.IOException; // Import the IOException class to handle errors public class WriteToFile < public static void main(String[] args) < try < FileWriter myWriter = new FileWriter("filename.txt"); myWriter.write("Files in Java might be tricky, but it is fun enough!"); myWriter.close(); System.out.println("Successfully wrote to the file."); >catch (IOException e) < System.out.println("An error occurred."); e.printStackTrace(); >> > 

To read the file above, go to the Java Read Files chapter.

Источник

Читайте также:  1с показать html документ
Оцените статью