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);
        }
      }
    }
  }
}

Properties File in Java öffnen und auslesen

Konfigurationen für eine Anwendung sollte man nach Möglichkeit in einer externen Datei auslagern. Java unterstützt dieses Konzept durch sog. „Properties“, die in einer Datei gespeichert werden und nach dem Key/Value-Prinzip ausgelesen werden können. Eine einfache .properties-Datei könnte wie folgt aussehen:

connection.properties

1
2
3
4
5
user=root
password=my-secret-password
host=localhost
port=3306
database=my-database

Den Wert „root“ des Schlüssels „user“ kann man dann mit folgendem Code-Schnippsel auslesen:

1
2
3
4
5
6
7
8
9
10
11
File propertiesFile = new File("./src/resources/connection.properties");
Properties properties = new Properties();
 
if(propertiesFile.exists())
{
  BufferedInputStream bis = new BufferedInputStream(new FileInputStream(propertiesFile));
  properties.load(bis);
  bis.close();  
}
 
System.out.println(properties.getProperty("user"));

Mit Java 7 geht das Ganze noch etwas kompakter (dank try-with-resources):

1
2
3
4
5
6
7
8
9
10
File propertiesFile = new File("./src/resources/connection.properties");
Properties properties = new Properties();
 
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(propertiesFile))) {
  properties.load(bis);
} catch (Exception ex) {
  //
}
 
System.out.println(properties.getProperty("user"));