Write string to file with Java 7

With Java 7 it is very easy to read and write files. If you want to put a string into a file, then you can do the following:

Version 1

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
 
public class JavaApplication{
  public static void main(String[] args) throws IOException {
    String text = "Hello World.";
    Path target = Paths.get("C:/dev/temp/test.txt");
 
    InputStream is = new ByteArrayInputStream(text.getBytes());
    Files.copy(is, target, StandardCopyOption.REPLACE_EXISTING);
  }
}

You can also do this:

Version 2

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 JavaApplication6 {
 
  public static void main(String[] args) throws IOException {
    String text = "Hello World.";
    Path target = Paths.get("C:/dev/temp/test.txt");
 
    Path file = Files.createFile(target);
    Files.write(file, text.getBytes(), StandardOpenOption.WRITE);
  }
}

In older Java versions you can do it like this (but you should use some try-catch-blocks to close the streams):

Version 3

import java.io.*;
 
public class JavaApplication{
 
  public static void main(String[] args) throws IOException {
    String text = "Hello World.";
    File target = new File("C:/dev/temp/test.txt");
 
    FileOutputStream fos = new FileOutputStream(target, false);
    BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fos));
    br.write(text);
    br.flush();
    br.close();
    fos.flush();
    fos.close();
  }
}

With Java 7 you don’t need try-catch-blocks because you can use try-with-resources:

Version 4

import java.io.*;
 
public class JavaApplication{
 
  public static void main(String[] args) throws IOException {
    String text = "Hello World.";
    File target = new File("C:/dev/temp/test.txt");
 
    try (FileOutputStream fos = new FileOutputStream(target, false)) {
      try (BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fos))) {
        br.write(text);
        br.flush();
      }
      fos.flush();
    }
  }
}

Version 5

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class JavaApplication {
 
  public static void main(String[] args) {
    String text = "Hello World.";
    File target = new File("C:/dev/temp/test.txt");
 
    FileWriter writer = null;
    try {
      writer = new FileWriter(target, false);
      writer.write(text);
    } catch (IOException ex) {
      Logger.getLogger(JavaApplication.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException ex) {
          Logger.getLogger(JavaApplication.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }
  }
}

Ein Gedanke zu „Write string to file with Java 7“

  1. text.getBytes() will always give you some UTF-8 bytes. Windows for example use ISO 8859. Writing thy bytes will cause an UTF-8 textfile. A FileWriter encodes to the default char encoding which can cause another encoding. I didn’t have the defaults in my head, but I guess with windows you’ll have a ISO 8859 file when using a FileWriter.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.