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

Java-like startsWith() in JavaScript

In Java you have some cool String functions like startsWith which can be used like this:

public static void main(String[] args)
{
  boolean startsWith = "Hello World".startsWith("Hello");
  System.out.println(startsWith); // true
}

In JavaScript you can have something similar with a bit of work:

<script type="text/javascript">
  String.prototype.startsWith = function(pattern){
    return (this.match('^' + pattern) == pattern);
  }
 
  var startsWith = "Hello World".startsWith("Hello");
  document.write(startsWith); // true
</script>

How to use Enums for String values

That’s how you can use enumerations for string values:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
 * ISO 3166
 */
public enum Country
{
  DE
  {
    @Override
    public String toString()
    {
      return "Germany";
    }
  },
  IT
  {
    @Override
    public String toString()
    {
      return "Italy";
    }
  },
  US
  {
    @Override
    public String toString()
    {
      return "United States";
    }
  }
}
1
2
3
4
5
6
public static void main(String[] args)
{
  System.out.println(Country.DE); // Germany
  System.out.println(Country.IT); // Italy
  System.out.println(Country.US); // United States
}

How to count occurrences of a character in a String with Java?

Code sample:

public class CharacterCounter
{
  public static int countOccurrences(String find, String string)
  {
    int count = 0;
    int indexOf = 0;
 
    while (indexOf > -1)
    {
      indexOf = string.indexOf(find, indexOf + 1);
      if (indexOf > -1)
        count++;
    }
 
    return count;
  }
}

Method call:

int occurrences = CharacterCounter.countOccurrences("l", "Hello World.");
System.out.println(occurrences); // 3

You can also count the occurrences of characters in a string by using the Apache commons lang library with the following one-liner:

int count = StringUtils.countMatches("a.b.c.d", ".");

If you are using the Sping Framework then you can do:

int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");

If you want to be really smart (and don’t want to use a loop), then you can also use this one here:

int count = string.length() - string.replace(find, "").length();

How to parse JSON with jQuery

With jQuery you could easily parse a JSON (which is an object in JavaScript Object Notation). The method parseJSON of jQuery translates the JSON even into the corresponding JavaScript data types. As an example I have chosen the following JSON:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
        "firstName": "Joe",
        "lastName" : "Black",
        "age"      : 28,
        "address"  :
        {
          "streetAddress": "1st Street",
          "city"         : "New York",
          "state"        : "NY",
          "postalCode"   : "10021"
        },
        "phoneNumber":
        [
          {
            "type"  : "home",
            "number": "212555-1234"
          },
          {
            "type"  : "fax",
            "number": "646555-4567"
          }
        ],
        "married" : true,
        "developer" : true	
}

This JSON contains nested objects like address, an array like phoneNumber and key-value pairs of different types like firstName (string), age (number) and married (boolean).

Here it is shown how it is parsed:
How to parse JSON with jQuery weiterlesen

String Templates mit Java (Tausend Wege führen nach Rom)

Um lange Zeichenketten (Strings) mit Werten zu füllen, bietet sich das Java MessageFormat an:

1
2
3
4
5
6
7
8
9
10
11
12
  public static void main(String[] args) throws Exception
  {
    String template = "My name is {0} {1}."
            + System.getProperty("line.separator", "\r\n")
            + "I am {2} years old.";
    Object[] values = new Object[]
    {
      "Benny", "Neugebauer", 24
    };
    String sentence = MessageFormat.format(template, values);
    System.out.println(sentence);
  }

Die Ausgabe wäre hierfür:

My name is Benny Neugebauer.
I am 24 years old.

Möglich wäre auch dieser Einzeiler:

String sentence = String.format("My Name is %s %s.%sI am %d yars old.", "Benny", "Neugebauer",  System.getProperty("line.separator"), 24);

Man könnte ebenso String Templates verwenden, müsste dann aber Bibliotheken wie etwa ANTLR (Five minute Introduction in ANTLR String Templates) verwenden. Natürlich kann man Strings auch verketten (konkatenieren), was aber wenig übersichtlich ist:

1
2
3
4
5
6
7
8
9
10
    String sentence = "My Name is "
            +"Benny"
            +" "
            +"Neugebauer"
            +"."
            +System.getProperty("line.separator")
            +"I am "
            +24
            +" years old.";
    System.out.println(sentence);

Hinsichtlich der Performanz, sind String Builder besser geeignet als die Konkatenation von Zeichenketten:

1
2
3
4
    StringBuilder sb = new StringBuilder("My name is ").append("Benny ");
    sb.append("Neugebauer").append(".").append(System.getProperty("line.separator"));
    sb.append("I am").append(24).append(" years old.");
    System.out.println(sb.toString());

Wie man an diesen kurzen Beispielen sieht gibt es viele Möglichkeiten, die zum Ergebnis führen. Mir gefällt derzeit das Message Format am besten. Das Message Format ist für den Standard Java-Logger (java.util.logging.Logger) sogar das von NetBeans 7 bevorzugte Format für Log-Nachrichten.