Java copy text to file

Java – How to save a String to a File

In Java, there are many ways to write a String to a File.

1. Java 11 – Files.writeString

Finally, a new method added in java.nio to save a String into a File easily.

 package com.mkyong; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class StringToFileJava11 < public static void main(String[] args) < String content = "Hello World \r\nJava!\r\n"; String path = "c:\\projects\\app.log"; try < // Java 11 , default StandardCharsets.UTF_8 Files.writeString(Paths.get(path), content); // encoding // Files.writeString(Paths.get(path), content, StandardCharsets.US_ASCII); // extra options // Files.writeString(Paths.get(path), content, // StandardOpenOption.CREATE, StandardOpenOption.APPEND); >catch (IOException e) < e.printStackTrace(); >> > 

2. Java 7 – Files.write

 package com.mkyong; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class StringToFileJava7 < public static void main(String[] args) < String content = "Hello World \r\nJava!\r\n"; String path = "c:\\projects\\app.log"; try < // Java 7 Files.write(Paths.get(path), content.getBytes()); // encoding // Files.write(Paths.get(path), content.getBytes(StandardCharsets.UTF_8)); // extra options // Files.write(Paths.get(path), content.getBytes(), // StandardOpenOption.CREATE, StandardOpenOption.APPEND); >catch (IOException e) < e.printStackTrace(); >> > 

3. Apache Commons IO

 package com.mkyong; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; public class CommonsIOExample < public static void main(String[] args) < String content = "Hello World \r\nJava!\r\n"; String path = "c:\\projects\\app2.log"; try < FileUtils.writeStringToFile(new File(path), content, StandardCharsets.UTF_8); // append // FileUtils.writeStringToFile(new File(path), content, StandardCharsets.UTF_8, true); >catch (IOException e) < e.printStackTrace(); >> > 

4. BufferedWriter

 package com.mkyong; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class BufferedWriterExample < public static void main(String[] args) < String content = "Hello World \r\nJava!\r\n"; String path = "c:\\projects\\app.log"; try (FileWriter writer = new FileWriter(path); BufferedWriter bw = new BufferedWriter(writer)) < bw.write(content); >catch (IOException e) < e.printStackTrace(); >> > 

4.2 Or like this, close all resources manually 🙂

 package com.mkyong; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class BufferedWriterExampleBeforeJava7 < public static void main(String[] args) < String content = "Hello World \r\nJava!\r\n"; String path = "c:\\projects\\app.log"; BufferedWriter bw = null; FileWriter fw = null; try < fw = new FileWriter(path); bw = new BufferedWriter(fw); bw.write(content); >catch (IOException e) < e.printStackTrace(); >finally < try < if (bw != null) bw.close(); if (fw != null) fw.close(); >catch (IOException ex) < ex.printStackTrace(); >> > > 

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Источник

Write Text to a File in Java

In this tutorial we are going to learn how to write text to a text file in a Java application. By different Java example programs we will explore different approaches to write a String into a text file using Java core classes.

Читайте также:  Openshift java heap space

Using Java NIO Files.write() static method

Following program to create a new file named test.txt and write text using Files.write() method.

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FilesWriteExample1  public static void main(String. args)  try  String fileName = "test.txt"; Path filePath = Paths.get(fileName); String contentToAppendToFile = "Simple Solution"; // Convert String into byte array and write to file Files.write(filePath, contentToAppendToFile.getBytes(), StandardOpenOption.CREATE); > catch (IOException e)  e.printStackTrace(); > > >

By using option StandardOpenOption.APPEND we can append text to an existing file.

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FilesWriteExample2  public static void main(String. args)  try  String fileName = "test.txt"; Path filePath = Paths.get(fileName); String contentToAppendToFile = "Simple Solution"; // Append to existing file. Files.write(filePath, contentToAppendToFile.getBytes(), StandardOpenOption.APPEND); > catch (IOException e)  e.printStackTrace(); > > >

The above append example will throw an error message when the file we are trying to write does not exist.

java.nio.file.NoSuchFileException: test.txt at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97) at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102) at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:230) at java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:434) at java.nio.file.Files.newOutputStream(Files.java:216) at java.nio.file.Files.write(Files.java:3292) at FilesWriteExample2.main(FilesWriteExample2.java:15)

To fix this error and make the application create a new file when it doesn’t exist and append when there is a file then we can add the option StandardOpenOption.CREATE as the following example.

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FilesWriteExample3  public static void main(String. args)  try  String fileName = "test.txt"; Path filePath = Paths.get(fileName); String contentToAppendToFile = "Simple Solution"; // use 2 options to create file if it doesn't exist // and append if file exist. Files.write(filePath, contentToAppendToFile.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); > catch (IOException e)  e.printStackTrace(); > > >

Files class also provides a method to allow writing a list of String.

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; public class FilesWriteExample4  public static void main(String. args)  try  String fileName = "test.txt"; Path filePath = Paths.get(fileName); ListString> contentToWrite = new ArrayList<>(); contentToWrite.add("Line 1"); contentToWrite.add("Line 2"); contentToWrite.add("Line 3"); // write a list of String Files.write(filePath, contentToWrite, StandardOpenOption.CREATE, StandardOpenOption.APPEND); > catch (IOException e)  e.printStackTrace(); > > >

Using Java NIO Files.newBufferedWriter() static method

Following Java program to show how to use Files.newBufferedWriter() to open existing files for writing or creating new files for writing text.

import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FilesNewBufferedWriterExample  public static void main(String. args)  try  String fileName = "test.txt"; Path filePath = Paths.get(fileName); BufferedWriter bufferedWriter = Files.newBufferedWriter(filePath, StandardOpenOption.CREATE, StandardOpenOption.APPEND); bufferedWriter.write("Line 1"); bufferedWriter.newLine(); bufferedWriter.write("Line 2"); bufferedWriter.newLine(); bufferedWriter.write("Line 3"); bufferedWriter.close(); > catch (IOException e)  e.printStackTrace(); > > >

Using Java IO FileWriter

import java.io.FileWriter; import java.io.IOException; public class FileWriterExample1  public static void main(String. args)  String fileName = "test.txt"; // use FileWriter to write text file try(FileWriter fileWriter = new FileWriter(fileName))  fileWriter.write("Line 1\n"); fileWriter.write("Line 2\n"); > catch (IOException e)  e.printStackTrace(); > > >

Using Java IO BufferedWriter and FileWriter

Using BufferedWriter to handle large file.

import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class FileWriterExample2  public static void main(String. args)  String fileName = "test.txt"; // use FileWriter with BufferedWriter try(FileWriter fileWriter = new FileWriter(fileName); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter))  bufferedWriter.write("Line 1"); bufferedWriter.newLine(); bufferedWriter.write("Line 2"); > catch (IOException e)  e.printStackTrace(); > > >

Using Java IO PrintWriter

import java.io.IOException; import java.io.PrintWriter; public class PrintWriterExample  public static void main(String. args)  String fileName = "test.txt"; // use PrintWriter to write text file try(PrintWriter printWriter = new PrintWriter(fileName))  printWriter.write("Line 1"); printWriter.write("\n"); printWriter.write("Line 2"); > catch (IOException e)  e.printStackTrace(); > > >

Using Java IO FileOutputStream, OutputStreamWriter and BufferedWriter

import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class BufferedWriterExample  public static void main(String. args)  String fileName = "test.txt"; try(FileOutputStream fileOutputStream = new FileOutputStream(fileName); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter))  bufferedWriter.write("Line 1"); bufferedWriter.newLine(); bufferedWriter.write("Line 2"); > catch (IOException e)  e.printStackTrace(); > > >

Источник

Java Write to File — 4 Ways to Write File in Java

Java Write to File - 4 Ways to Write File in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java provides several ways to write to file. We can use FileWriter, BufferedWriter, java 7 Files and FileOutputStream to write a file in Java.

Java Write to File

java write to file, write file in java

Let’s have a brief look at four options we have for java write to file operation.

  1. FileWriter: FileWriter is the simplest way to write a file in Java. It provides overloaded write method to write int, byte array, and String to the File. You can also write part of the String or byte array using FileWriter. FileWriter writes directly into Files and should be used only when the number of writes is less.
  2. BufferedWriter: BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better. You should use BufferedWriter when the number of write operations is more.
  3. FileOutputStream: FileWriter and BufferedWriter are meant to write text to the file but when you need raw stream data to be written into file, you should use FileOutputStream to write file in java.
  4. Files: Java 7 introduced Files utility class and we can write a file using its write function. Internally it’s using OutputStream to write byte array into file.

Java Write to File Example

Here is the example showing how we can write a file in java using FileWriter, BufferedWriter, FileOutputStream, and Files in java. WriteFile.java

package com.journaldev.files; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; public class WriteFile < /** * This class shows how to write file in java * @param args * @throws IOException */ public static void main(String[] args) < String data = "I will write this String to File in Java"; int noOfLines = 10000; writeUsingFileWriter(data); writeUsingBufferedWriter(data, noOfLines); writeUsingFiles(data); writeUsingOutputStream(data); System.out.println("DONE"); >/** * Use Streams when you are dealing with raw data * @param data */ private static void writeUsingOutputStream(String data) < OutputStream os = null; try < os = new FileOutputStream(new File("/Users/pankaj/os.txt")); os.write(data.getBytes(), 0, data.length()); >catch (IOException e) < e.printStackTrace(); >finally < try < os.close(); >catch (IOException e) < e.printStackTrace(); >> > /** * Use Files class from Java 1.7 to write files, internally uses OutputStream * @param data */ private static void writeUsingFiles(String data) < try < Files.write(Paths.get("/Users/pankaj/files.txt"), data.getBytes()); >catch (IOException e) < e.printStackTrace(); >> /** * Use BufferedWriter when number of write operations are more * It uses internal buffer to reduce real IO operations and saves time * @param data * @param noOfLines */ private static void writeUsingBufferedWriter(String data, int noOfLines) < File file = new File("/Users/pankaj/BufferedWriter.txt"); FileWriter fr = null; BufferedWriter br = null; String dataWithNewLine=data+System.getProperty("line.separator"); try< fr = new FileWriter(file); br = new BufferedWriter(fr); for(int i = noOfLines; i>0; i--) < br.write(dataWithNewLine); >> catch (IOException e) < e.printStackTrace(); >finally < try < br.close(); fr.close(); >catch (IOException e) < e.printStackTrace(); >> > /** * Use FileWriter when number of write operations are less * @param data */ private static void writeUsingFileWriter(String data) < File file = new File("/Users/pankaj/FileWriter.txt"); FileWriter fr = null; try < fr = new FileWriter(file); fr.write(data); >catch (IOException e) < e.printStackTrace(); >finally < //close resources try < fr.close(); >catch (IOException e) < e.printStackTrace(); >> > > 

These are the standard methods to write a file in java and you should choose any one of these based on your project requirements. That’s all for Java write to file example.

You can checkout more Java IO examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью