Writing content to file in java

Writing to a File in Java

When working on an enterprise application, sometimes it is needed to write the text or binary data into files in Java e.g. writing user-generated reports into the filesystem.

Though there are multiple ways of writing the files in Java, let’s quickly go through a few of them for quick reference when it is needed.

1. Using Files.writeString() and Files.write()

With the method writeString() introduced in Java 11, we can write a String into a file using a single-line statement.

  • As the name suggests, writeString() method is used to write the character data into files.
  • All characters are written as they are, including the line separators. No extra characters are added.
  • By default, UTF-8 character encoding is used.
  • It throws IOException if an I/O error occurs writing to or creating the file, or the text cannot be encoded using the specified charset.
Path filePath = Path.of("demo.txt"); String content = "hello world !!"; Files.writeString(filePath, content);

Files class another method write() since Java 7 and it works similar to writeString(). The write() method can be used to write the raw data in bytes or to write the strings in lines.

Path filePath = Path.of("demo.txt"); String content = "hello world !!"; //Write bytes Files.write(filePath, content.getBytes()); //Write lines List lines = Arrays.asList("a", "b", "c"); Files.write(filePath, lines, StandardCharsets.UTF_8);

2. Fast Writing FileChannel and ByteBuffer

Читайте также:  Как инициализировать переменную в питоне

FileChannel can be used for reading, writing, mapping, and manipulating a file. If we are writing the large files, FileChannel can be faster than standard IO.

File channels are safe for use by multiple concurrent threads.

Path fileName = Path.of("demo.txt"); String content = "hello world !!"; try ( RandomAccessFile stream = new RandomAccessFile(filePath.toFile(),"rw"); FileChannel channel = stream.getChannel();)

BufferedWriter the simplest way to write the content to a file. It writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriter and OutputStreamWriter .

As it buffers before writing, so it results in fewer IO operations, so it improves the performance.

Path filePath = Path.of("demo.txt"); String content = "hello world !!"; try (BufferedWriter writer = new BufferedWriter( new FileWriter(filePath.toFile())))

4. Using FileWriter or PrintWriter

FileWriter the most clean way to write files. The syntax is self-explanatory and easy to read and understand. FileWriter writes directly into the file (less performance) and should be used only when the number of writes is less.

Path filePath = Path.of("demo.txt"); String content = "hello world !!"; try(FileWriter fileWriter = new FileWriter(filePath.toFile()))

Use PrintWriter to write formatted text to a file. This class implements all of the print methods found in PrintStream , so you can use all formats which you use with System.out.println() statements.

Path filePath = Path.of("demo.txt"); String content = "hello world !!"; try(FileWriter fileWriter = new FileWriter(filePath.toFile()); PrintWriter printWriter = new PrintWriter(fileWriter);)

Use FileOutputStream to write binary data to a file. FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter .

Path filePath = Path.of("demo.txt"); String content = "hello world !!"; try(FileOutputStream outputStream = new FileOutputStream(filePath.toFile()))

DataOutputStream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.

Path filePath = Path.of("demo.txt"); String content = "hello world !!"; try ( FileOutputStream outputStream = new FileOutputStream(filePath.toFile()); DataOutputStream dataOutStream = new DataOutputStream(new BufferedOutputStream(outputStream));)
  1. If we try to write to a file that doesn’t exist, the file will be created first and no exception will be thrown (except using Path method).
  2. Always close the output stream after writing the file content to release all resources. It will also help in not corrupting the file.
  3. Use PrintWriter is used to write formatted text.
  4. Use FileOutputStream to write binary data.
  5. Use DataOutputStream to write primitive data types.
  6. Use FileChannel to write larger files. It is the preferred way of writing filesin Java 8 as well.

Источник

Writing content to file in java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

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.

Источник

Java Write To File Examples

Last updated: 02 February 2020 In this post we will look at five different examples on how to write to a file using Java. The code sinppets check to see if the file exists before writing to the file, otherwise a file is created.

Write to file using BufferedWriter

import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class WriteToFile < public static void main( String[] args ) < try < String content = "Content to write to file"; //Name and path of the file File file = new File("writefile.txt"); if(!file.exists())< file.createNewFile(); >FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); > catch(IOException ex) < System.out.println("Exception occurred:"); ex.printStackTrace(); >> > 

Note: If we want to append to a file, we need to initialize the FileWriter with the true parameter:

FileWriter fw = new FileWriter(file, true); 

Write to file using PrintWriter

import java.io.*; public class WriteToFile < public static void main( String[] args ) < try < String content = "Content to write to file"; //Name and path of the file File file = new File("writefile.txt"); if(!file.exists())< file.createNewFile(); >FileWriter fw = new FileWriter(file); PrintWriter bw = new PrintWriter(fw); bw.write(content); bw.close(); > catch(IOException ex) < System.out.println("Exception occurred:"); ex.printStackTrace(); >> > 

Write to file using FileOutputStream

import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class WriteToFile < public static void main( String[] args ) < try < String content = "Content to write to file"; //Name and path of the file File file = new File("writefile.txt"); if(!file.exists())< file.createNewFile(); >FileOutputStream outStream = new FileOutputStream(file); byte[] strToBytes = content.getBytes(); outStream.write(strToBytes); outStream.close(); > catch(IOException ex) < System.out.println("Exception occurred:"); ex.printStackTrace(); >> > 

Write to file using Files class

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class WriteToFile < public static void main( String[] args ) < Path path = Paths.get("writefile.txt"); String content = "Content to write to file"; try < byte[] bytes = content.getBytes(); Files.write(path, bytes); >catch(IOException ex) < System.out.println("Exception occurred:"); ex.printStackTrace(); >> > 

Write to file using DataOutputStream

import java.io.*; public class WriteToFile < public static void main( String[] args ) < String content = "Content to write to file"; try < File file = new File("writefile.txt"); if(!file.exists())< file.createNewFile(); >FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream dataOutStream = new DataOutputStream(bos); dataOutStream.writeUTF(content); dataOutStream.close(); > catch(IOException ex) < System.out.println("Exception occurred:"); ex.printStackTrace(); >> > 

Источник

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