Save into a file java

How do I create a file and write to it?

May I ask why simple is important when you can write a function/procedure/method that contains the code needed; then you’d simply have to call that function/procedure/method. Is it just to save some typing?

35 Answers 35

Note that each of the code samples below may throw IOException . Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling.

Note that each of the code samples below will overwrite the file if it already exists

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8"); writer.println("The first line"); writer.println("The second line"); writer.close(); 
byte data[] = . FileOutputStream out = new FileOutputStream("the-file-name"); out.write(data); out.close(); 

Java 7+ users can use the Files class to write to files:

List lines = Arrays.asList("The first line", "The second line"); Path file = Paths.get("the-file-name.txt"); Files.write(file, lines, StandardCharsets.UTF_8); //Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND); 
byte data[] = . Path file = Paths.get("the-file-name"); Files.write(file, data); //Files.write(file, data, StandardOpenOption.APPEND); 
try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("filename.txt"), "utf-8")))

There are useful utilities for that though:

Note also that you can use a FileWriter , but it uses the default encoding, which is often a bad idea — it’s best to specify the encoding explicitly.

Below is the original, prior-to-Java 7 answer

Writer writer = null; try < writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("filename.txt"), "utf-8")); writer.write("Something"); >catch (IOException ex) < // Report >finally < try catch (Exception ex) > 

If you already have the content you want to write to the file (and not generated on the fly), the java.nio.file.Files addition in Java 7 as part of native I/O provides the simplest and most efficient way to achieve your goals.

Basically creating and writing to a file is one line only, moreover one simple method call!

The following example creates and writes to 6 different files to showcase how it can be used:

Charset utf8 = StandardCharsets.UTF_8; List lines = Arrays.asList("1st line", "2nd line"); byte[] data = ; try < Files.write(Paths.get("file1.bin"), data); Files.write(Paths.get("file2.bin"), data, StandardOpenOption.CREATE, StandardOpenOption.APPEND); Files.write(Paths.get("file3.txt"), "content".getBytes()); Files.write(Paths.get("file4.txt"), "content".getBytes(utf8)); Files.write(Paths.get("file5.txt"), lines, utf8); Files.write(Paths.get("file6.txt"), lines, utf8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); >catch (IOException e)
public class Program < public static void main(String[] args) < String text = "Hello world"; BufferedWriter output = null; try < File file = new File("example.txt"); output = new BufferedWriter(new FileWriter(file)); output.write(text); >catch ( IOException e ) < e.printStackTrace(); >finally < if ( output != null ) < try < output.close(); >catch (IOException e) < e.printStackTrace(); >> > > > 

A very simple way to create and write to a file in Java:

import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; public class CreateFiles < public static void main(String[] args) < try< // Create new file String content = "This is the content to write into create file"; String path="D:\\a\\hi.txt"; File file = new File(path); // If file doesn't exists, then create it if (!file.exists()) < file.createNewFile(); >FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); // Write in file bw.write(content); // Close connection bw.close(); > catch(Exception e) < System.out.println(e); >> > 

Here’s a little example program to create or overwrite a file. It’s the long version so it can be understood more easily.

import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; public class writer < public void writing() < try < //Whatever the file path is. File statText = new File("E:/Java/Reference/bin/images/statsTest.txt"); FileOutputStream is = new FileOutputStream(statText); OutputStreamWriter osw = new OutputStreamWriter(is); Writer w = new BufferedWriter(osw); w.write("POTATO. "); w.close(); >catch (IOException e) < System.err.println("Problem writing to the file statsTest.txt"); >> public static void main(String[]args) < writer write = new writer(); write.writing(); >> 
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8))) < writer.write("text to write"); >catch (IOException ex) < // Handle me >

Using try() will close stream automatically. This version is short, fast (buffered) and enables choosing encoding.

Читайте также:  Операция факториал в питоне

This feature was introduced in Java 7.

Here we are entering a string into a text file:

String content = "This is the content to write into a file"; File file = new File("filename.txt"); FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); // Be sure to close BufferedWriter 

We can easily create a new file and add content into it.

There are many ways of writing to a file. Each has its benefits, and each might be simplest in a given scenario.

This answer is centred on Java 8, and tries to cover all the details needed for the Java Professional Exam. Classes involved include:

. ├── OutputStream │ └── FileOutputStream ├── Writer │ ├── OutputStreamWriter │ │ └── FileWriter │ ├── BufferedWriter │ └── PrintWriter (Java 5+) └── Files (Java 7+) 

There are 5 main ways of writing to a file:

┌───────────────────────────┬────────────────────────┬─────────────┬──────────────┐ │ │ Buffer for │ Can specify │ Throws │ │ │ large files? │ encoding? │ IOException? │ ├───────────────────────────┼────────────────────────┼─────────────┼──────────────┤ │ OutputStreamWriter │ Wrap in BufferedWriter │ Y │ Y │ │ FileWriter │ Wrap in BufferedWriter │ │ Y │ │ PrintWriter │ Y │ Y │ │ │ Files.write() │ │ Y │ Y │ │ Files.newBufferedWriter() │ Y │ Y │ Y │ └───────────────────────────┴────────────────────────┴─────────────┴──────────────┘ 

Each has its own distinctive benefits:

  • OutputStreamWriter — The most basic way before Java 5
  • FileWriter – Optional append constructor argument
  • PrintWriter – Lots of methods
  • Files.write() – Create and write to a file in a single call
  • Files.newBufferedWriter() – Makes it easy to write large files

Below are details of each.

FileOutputStream

This class is meant for writing streams of raw bytes. All the Writer approaches below rely on this class, either explicitly or under the hood.

try (FileOutputStream stream = new FileOutputStream("file.txt");) < byte data[] = "foo".getBytes(); stream.write(data); >catch (IOException e) <> 

Note that the try-with-resources statement takes care of stream.close() and that closing the stream flushes it, like stream.flush() .

OutputStreamWriter

This class is a bridge from character streams to byte streams. It can wrap a FileOutputStream , and write strings:

Charset utf8 = StandardCharsets.UTF_8; try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File("file.txt")), utf8)) < writer.write("foo"); >catch (IOException e) <> 

BufferedWriter

This class writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

It can wrap an OutputStreamWriter :

try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("file.txt"))))) < writer.write("foo"); writer.newLine(); // method provided by BufferedWriter >catch (IOException e) <> 

Pre Java 5 this was the best approach for large files (with a regular try/catch block).

Читайте также:  Php формирование документов word

FileWriter

This is a subclass of the OutputStreamWriter , and is a convenience class for writing character files:

boolean append = false; try(FileWriter writer = new FileWriter("file.txt", append) ) < writer.write("foo"); writer.append("bar"); >catch (IOException e) <> 

The key benefit is that it has an optional append constructor argument, which determines whether it appends to or overwrites the existing file. Note that the append/overwrite behaviour is not controlled by the write() and append() methods, which behave in nearly the same way.

  • There is no buffering, but to handle large files it can be wrapped in a BufferedWriter .
  • FileWriter uses the default encoding. It’s often preferable to specify encoding explicitly

PrintWriter

This class prints formatted representations of objects to a text-output stream. Under the hood it is the same as the BufferedWriter approach above ( new BufferedWriter(new OutputStreamWriter(new FileOutputStream(. ))) ). PrintWriter was introduced in Java 5 as a convenient way to call this idiom, and adds additional methods such as printf() and println() .

Methods in this class don’t throw I/O exceptions. You can check errors by calling checkError() . The destination of a PrintWriter instance can be a File, OutputStream or Writer. Here is an example of writing to a file:

try (PrintWriter writer = new PrintWriter("file.txt", "UTF-8")) < writer.print("foo"); writer.printf("bar %d $", "a", 1); writer.println("baz"); >catch (FileNotFoundException e) < >catch (UnsupportedEncodingException e) <> 

When writing to an OutputStream or Writer there is an optional autoFlush constructor parameter, which is false by default. Unlike the FileWriter , it will overwrite any existing file.

Files.write()

Java 7 introduced java.nio.file.Files . Files.write() lets you create and write to a file in a single call.

@icza’s answer shows how to use this method. A couple of examples:

Charset utf8 = StandardCharsets.UTF_8; List lines = Arrays.asList("foo", "bar"); try < Files.write(Paths.get("file.txt"), "foo".getBytes(utf8)); Files.write(Paths.get("file2.txt"), lines, utf8); >catch (IOException e) <> 

This does not involve a buffer, so it’s not suitable for large files.

Files.newBufferedWriter()

Java 7 also introduced Files.newBufferedWriter() which makes it easy to get a BufferedWriter :

Charset utf8 = StandardCharsets.UTF_8; try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("file.txt"), utf8)) < writer.write("foo"); >catch (IOException e) <> 

This is similar to PrintWriter , with the downside of not having PrintWriter’s methods, and the benefit that it doesn’t swallow exceptions.

Источник

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.
Читайте также:  Charsequence interface in java lang

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.

Источник

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