51

I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner :D

I searched the web and found this code, but I understand 50% of it.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample {
public static void main(String[] args) {
    try {

        String content = "This is the content to write into file";

        File file = new  File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

informatik01
  • 16,038
  • 10
  • 74
  • 104
Georgi Koemdzhiev
  • 11,421
  • 18
  • 62
  • 126
  • I think there is no easier code than this. Could you specify what you dont understand? – Henrik Apr 04 '14 at 09:58
  • Thank you for your responce! Well I dont understand the what the FileWriter and BufferedWriter classes do. Oh and the carch(IOExeption) part at the end. Please can you explain me briefly what thay do. – Georgi Koemdzhiev Apr 04 '14 at 10:12

9 Answers9

111

With Java 7 and up, a one liner using Files:

String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());
Graham Russell
  • 997
  • 13
  • 24
dazito
  • 7,740
  • 15
  • 75
  • 117
22

You could do this by using JAVA 7 new File API.

code sample: `

public class FileWriter7 {
    public static void main(String[] args) throws IOException {
        List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
        String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
        writeSmallTextFile(lines, filepath);
    }

    private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
        Path path = Paths.get(aFileName);
        Files.write(path, aLines, StandardCharsets.UTF_8);
    }
}

`

Dilip Kumar
  • 2,504
  • 2
  • 17
  • 33
  • 1
    Note that this is by far the simplest since all you really need is: Files.write(file.toPath(), content.getBytes()); to meet the original question's goals. – Bill K Jul 17 '15 at 23:51
20

You can use FileUtils from Apache Commons:

import org.apache.commons.io.FileUtils;

final File file = new File("test.txt");
FileUtils.writeStringToFile(file, "your content", StandardCharsets.UTF_8);
Graham Russell
  • 997
  • 13
  • 24
Jakub H
  • 2,130
  • 9
  • 16
  • 1
    If you have multiple lines, you can use `.writeLines()`. And it closes everything for you properly in the case of exceptions, and no security issues with `System.getProperty`. All this stuff is a pain without commons. – Andrew Aug 11 '14 at 07:27
7

Appending the file FileWriter(String fileName, boolean append)

try {   // this is for monitoring runtime Exception within the block 

        String content = "This is the content to write into file"; // content to write into the file

        File file = new  File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt"); // here file not created here

        // if file doesnt exists, then create it
        if (!file.exists()) {   // checks whether the file is Exist or not
            file.createNewFile();   // here if file not exist new file created 
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // creating fileWriter object with the file
        BufferedWriter bw = new BufferedWriter(fw); // creating bufferWriter which is used to write the content into the file
        bw.write(content); // write method is used to write the given content into the file
        bw.close(); // Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect. 

        System.out.println("Done");

    } catch (IOException e) { // if any exception occurs it will catch
        e.printStackTrace();
    }
newuser
  • 8,338
  • 2
  • 25
  • 33
  • Thank you for the comments! Now the picture is more clear! :) – Georgi Koemdzhiev Apr 04 '14 at 19:45
  • @BogGogo see the updated answer to append the file content without erase the previous content. FileWriter having the append file option. The default value of the attribute is false. – newuser Apr 07 '14 at 01:37
4

Your code is the simplest. But, i always try to optimize the code further. Here is a sample.

try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./output/output.txt")))) {
    bw.write("Hello, This is a test message");
    bw.close();
    }catch (FileNotFoundException ex) {
    System.out.println(ex.toString());
    }
  • I don't think your FileWriter will be closed if you do it that way. Not sure if it matters though. – Shannon Mar 01 '17 at 00:42
4

Files.write() the simple solution as @Dilip Kumar said. I used to use that way untill I faced an issue, can not affect line separator (Unix/Windows) CR LF.

So now I use a Java 8 stream file writing way, what allows me to manipulate the content on the fly. :)

List<String> lines = Arrays.asList(new String[] { "line1", "line2" });

Path path = Paths.get(fullFileName);
try (BufferedWriter writer = Files.newBufferedWriter(path)) {   
    writer.write(lines.stream()
                      .reduce((sum,currLine) ->  sum + "\n"  + currLine)
                      .get());
}     

In this way, I can specify the line separator or I can do any kind of magic like TRIM, Uppercase, filtering etc.

Laszlo Lugosi
  • 3,669
  • 1
  • 21
  • 17
3
String content = "your content here";
Path path = Paths.get("/data/output.txt");
if(!Files.exists(path)){
    Files.createFile(path);
}
BufferedWriter writer = Files.newBufferedWriter(path);
writer.write(content);
laughing buddha
  • 351
  • 3
  • 10
3

In Java 11 or Later, writeString can be used from java.nio.file.Files,

String content = "This is my content";
String fileName = "myFile.txt";
Files.writeString(Paths.get(fileName), content); 

With Options:

Files.writeString(Paths.get(fileName), content, StandardOpenOption.CREATE)

More documentation about the java.nio.file.Files and StandardOpenOption

Praveen
  • 1,791
  • 3
  • 20
  • 33
-2
File file = new File("path/file.name");
IOUtils.write("content", new FileOutputStream(file));

IOUtils also can be used to write/read files easily with java 8.

ruks
  • 376
  • 3
  • 8