Languages
[Edit]
EN

Java - save string to file

1 points
Created by:
Palusbug
515

In this article we would like to show you how to save string to file in java.

Using BufferedWriter

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SaveFileExample {

    public static void main(String[] args) throws IOException {

        String text = "Hello world";
        Path path = Paths.get("C:\\test\\my-file.txt");

        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            writer.write(text);
            writer.flush(); // ensure long text will be saved
        }
    }
}

By default Files.newBufferedWriter uses StandardCharsets.UTF_8 (java.nio.charset.StandardCharsets.UTF_8) encoding.

Using BufferedWriter with append to existing file

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 SaveFileAppendExample {

    public static void main(String[] args) throws IOException {

        String text = "--Hello world--";
        Path path = Paths.get("C:\\test\\my-file.txt");

        if (!Files.exists(path)) {
            Files.createFile(path);
        }

        try (BufferedWriter writer = Files.newBufferedWriter(path, 
                StandardOpenOption.APPEND)) {
            writer.write(text);
            writer.append(", hello again");
            writer.flush(); // ensure long text will be saved
        }
    }
}

If we execture above code 2 times, the file will contains below output:

--Hello world--, hello again--Hello world--, hello again

If we use BufferedWriter with APPEND option we need to ensure the file we want to save our data to exists. If the file doesn't exits we will get exception, that's why in above code we check if file exists and if not we create new one.

Using PrintWriter

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

public class SaveFileExample2 {

    public static void main(String[] args) throws FileNotFoundException,
            UnsupportedEncodingException {

        String text = "Hello world";
        String path = "C:\\test\\my-file.txt";

        String charset = StandardCharsets.UTF_8.toString();
        try (PrintWriter writer = new PrintWriter(path, charset)) {
            writer.println(text);
            writer.flush(); // ensure long text will be saved
        }
    }
}

 

Alternative titles

  1. Java write text string to file
  2. Java save text string to file
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - file operations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join