java.util.ConcurrentModificationException vermeiden

Zur Ausgabe von Listen eignen sich foreach-Schleifen besonders gut. Man sollte jedoch vermeiden, innerhalb eines foreach-Blocks die Liste zu modifizieren, da die Datenstruktur der Liste während der Iteration für Veränderungen gesperrt ist. Ein Hinzufügen oder Löschen von Elemente führt somit zur java.util.ConcurrentModificationException.
java.util.ConcurrentModificationException vermeiden weiterlesen

How to get node attributes with Java SAX XML parser

Parsing XML from a String

import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
 
public class Main {
 
  public static void main(String[] args) throws Exception {
    // Prepare input stream
    String text = "<person number=\"72\"><name>Benny</name></person>";
 
    // Read input stream
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new StringReader(text)));
 
    // Output data
    NodeList elementsByTagName = document.getElementsByTagName("person");
    for (int i = 0; i &lt; elementsByTagName.getLength(); i++) {
      Node node = elementsByTagName.item(i);
      Element element = (Element) node;
      String attribute = element.getAttribute("number");
      System.out.println(attribute);
    }
  }
}

Parsing XML from a File

package com.welovecoding.parse.xml;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
 
public class Main {
 
  public static void main(String[] args) throws Exception {
    // Prepare input stream
    File file = new File("persons.xml");
    InputStream inputStream = new FileInputStream(file);
    Reader reader = new InputStreamReader(inputStream, "UTF-8");
    InputSource is = new InputSource(reader);
    is.setEncoding("UTF-8");
 
    // Read input stream
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(is);
 
    // Output data
    NodeList elementsByTagName = document.getElementsByTagName("person");
    for (int i = 0; i < elementsByTagName.getLength(); i++) {
      Node node = elementsByTagName.item(i);
      Element element = (Element) node;
      String attribute = element.getAttribute("number");
      System.out.println(attribute);
    }
  }
}

Result

72

How to use Iterator, for and foreach-loop in Java

Here is a very good example on how to use the Iterator, for and foreach-loop in Java:

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class JavaApplication {
 
  public static void main(String[] args) throws IOException {
    List<String> names = new ArrayList<>();
    names.add("Benny");
    names.add("Sarah");
    names.add("Daniel");
    names.add("Maria");
 
    // Iterator
    Iterator<String> iterator = names.iterator();
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
 
    // for
    for (int i = 0; i < names.size(); i++) {
      System.out.println(names.get(i));
    }
 
    // foreach
    for (String name : names) {
      System.out.println(name);
    }
  }
}

Create GraphML XML file with Java

With Blueprints it is very easy to create a XML file following the GraphML standard. All you need is this:

import com.tinkerpop.blueprints.pgm.Vertex;
import com.tinkerpop.blueprints.pgm.impls.tg.TinkerGraph;
import com.tinkerpop.blueprints.pgm.util.io.graphml.GraphMLWriter;
import java.io.FileOutputStream;
import java.io.OutputStream;
 
public class App {
 
  private static final String OUTPUT_FILE = "./res/graph.graphml";
 
  public static void main(String[] args) throws Exception {
    OutputStream out = new FileOutputStream(OUTPUT_FILE);
    TinkerGraph graph = new TinkerGraph();
 
    Vertex source = graph.addVertex("1");
    Vertex target = graph.addVertex("2");
    graph.addEdge("3", source, target, "connection");
 
    GraphMLWriter writer = new GraphMLWriter(graph);
    writer.outputGraph(out);
  }
}

This is what you will get then:

graph.graphml

<?xml version="1.0" ?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns">
  <graph id="G" edgedefault="directed">
    <node id="2"></node>
    <node id="1"></node>
    <edge id="3" source="1" target="2" label="connection"></edge>
  </graph>
</graphml>

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

How to parse GraphML files with a cool Java library

I’ve found this great GraphML reader and writer library: Blueprints. There is also a good documentation on how to use the GraphML library for reading XML-encoded graphs. Anyway, I think my example is better. 🙂
How to parse GraphML files with a cool Java library weiterlesen