Skip to content

Instantly share code, notes, and snippets.

@gennad
Created February 9, 2011 09:36
Show Gist options
  • Save gennad/818209 to your computer and use it in GitHub Desktop.
Save gennad/818209 to your computer and use it in GitHub Desktop.
Creates indents in the xml file
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* Main class of the application.
*
* <p>The application parses input files, seeks xml tags and creates valid hierarchy.</p>
* <p> The amount of indent is 2 spaces.</p>
* @author Gennadiy Zlobin <[email protected]>
* @since 1.0
*/
public class XmlIndenter {
/*
* Entry method of the application.
*
* <p> The main method which executes the logic.
* @param args Arguments of the application.
*/
public static void main(String[] args) {
boolean res = checkParams(args);
File file = new File(args[0]);
FileReader fr = null;
FileWriter fw = null;
BufferedReader br = null;
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
String s;
StringBuffer sb = new StringBuffer();
int numOfSpaces = 0;
Pattern p = Pattern.compile("\\<\\w");
Matcher m;
while ((s = br.readLine() ) != null) {
m = p.matcher(s);
if (! m.find(0)) { // Not open
if (s.indexOf("</") != -1) // And close
numOfSpaces -= 2;
}
String spaces = "";
for (int i = 0; i < numOfSpaces; i++) {
spaces += " ";
}
s = s.trim();
sb.append(spaces).append(s).append("\n");
if (m.find(0)) { // Open
if (s.indexOf("</") == -1) // And not close
numOfSpaces += 2;
}
}
fr.close();
fw = new FileWriter(file, false);
fw.write(sb.toString());
fw.close();
System.out.printf("The file '%s' is parsed successfully.\n", args[0]);
} catch (FileNotFoundException fnfe) {
System.out.println("File doesn't exist");
System.exit(1);
} catch (IOException ioe) {
System.out.println("IO Exception appeared");
System.exit(1);
}
}
/**
* Check param for validness.
*
* <p>Stops the application if params are invalid.</p>
* @param args Args of the application.
* @return If the params are correct, returns true, otherwise false.
*/
public static boolean checkParams(String[] args) {
if (args.length == 0) {
System.out.println("Usage: java XmlParser FILENAME");
System.exit(1);
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment