Java/JavaScript Tips on Append to File

This is Java/JavaScript Tips on Append content to file. I will introduce append file via command line, Java, and Node.JS (JavaScript).

To append file via command line, in Windows or Unix, you can do:

echo "test" >> a.txt

The file a.txt will be created if not exist at the first time. And the subsequence calls of >> will append the content to next line of the end of file.

To append file via Java, you can do:

PrintWriter pw = new PrintWriter(new FileWriter(new File("a.txt"), true)); 
pw.println("test");
pw.close();

The file a.txt will be created if not exist at the first time. And the subsequence calls of PrintWriter.println will append the content to next line of the end of file.

The interesting thing is I like to use PrintWriter, to call println, which I not need to append \n myself.

Notice the true variable at new FileWriter, this let Java know you want to append file, if you not provide this variable, Java will always overwrite the file but not appending.

To append file via JavaScript, you can do:

in asynchronous calls:

var fs = require('fs');
fs.appendFile('a.txt', 'content\n', function(err) {
 // some callback after append file
});

OR

in synchronize calls:

var fs = require('fs');
fs.appendFileSync('a.txt', 'content\n');

The file a.txt will be created if not exist at the first time. And the subsequence calls of appendFile or appendFileSync will append the content to next line of the end of file.

Node.JS provides asynchronous and synchronize versions for each File IO Calls. Refer the link here. Other than appendFile, for example, readFile/readFileSync, writeFile/writeFileSync.

Node.JS itself is a single threaded and asynchronous. It is always recommended to use asynchronous version of method instead of synchronize version, as synchronize version is a blocking calls. If the content need append to file is very very big, the calls will just hang there, Node.JS cannot handle other requests anymore. To learn how Node.JS back end works, refer here.

Java tips String concatenations using StringBuffer

Java provides StringBuffer and String. Always use StringBuffer when you want concatenate string. StringBuffer has better performance over String when doing simple string concatenation.

String is immutable, that something cannot be changed. When you concatenate using String, JVM actually create new Object for each concatenation. Create new Object is expensive. See below example.

When using String, you may doing something like:

String message = ""; // new object
message = message + "I am "; // another new
message = message + "25"; // another new
message = message + " years old"; // another new

When using StringBuffer, you will doing something like

StringBuffer sb = new StringBuffer(); // new object here
sb.append("I am ");
sb.append("25");
sb.append(" years old");
String message = sb.toString(); // another new

As you can see, by using String, you create a bunch of new objects. When you have more things to concatenate, more and more objects created, and again, creating new object is very expensive, and make application performance worse.

It is strongly recommended by using StringBuffer to append string, and at the last, call toString() to export the string content into String object, then you can use it for any purpose.

So for the example on Java tips on joining string with separator, the code can be changed to below:

private static String join_1(String[] array, String separator) {
	StringBuffer sb = new StringBuffer();
	String comma = "";
	for(int i = 0; i < array.length; i++) {
		sb.append(comma + array[i]);
		comma = separator;
	}
	return sb.toString();
}

private static String join_2(String[] array, String separator) {
        StringBuffer sb = new StringBuffer();
	for(int i = 0; i < array.length; i++) {
		sb.append(array[i] + separator);
	}
        String s = sb.toString();
	return s.substring(0, s.length() - separator.length());
}

Another note, when use String for concatenation, internally it will create StringBuffer to do actual concatenation. Refer this link for more information.

Java/JavaScript tips for removing list elements when iterating list

This is Java and JavaScript tips for same topic, removing list elements when iterating list.

In Java, we will use List as an example, as it is uncommon to remove element from an Array. In Javascript we will use Array as an example, as only Array is supported in JavaScript.

Introduction

To remove an element from a Java List, you will do

List someList = new ArrayList();
someList.add("two");
someList.add("one");
someList.add("three");
someList.remove(1); // to remove by index
someList.remove("one); // to remove by element value
System.out.println(someList);

To remove an element from a JavaScript Array, you will do

var someArray = ["two", "one", "three"];
someArray.splice(1, 1); // to remove by index
console.log(someArray);

What if you want to remove an element from a List or Array when you iterating the List, you want to remove it based on some conditions?

In Java, you may do

List someList = new ArrayList();
someList.add("two");
someList.add("one");
someList.add("three");

for(String item : someList) {
  if(item.equals("one")) {
    someList.remove(item); // #1
  }
  else if(item.equals("three")) {
    someList.remove(item); // #2
  }
}

Unfortunately, by doing this, you will get exception thrown.

By executing line #1, “one” is removed from someList, and next if you still continue the for loop, you will get exception as someList is modified, affecting the for loop execution.

The best way to remove item from a Java list is to use Iterator

List someList = new ArrayList();
someList.add("two");
someList.add("one");
someList.add("three");

Iterator it = someList.iterator();
while(it.hasNext()) {
  String item = it.next();
  if(item.equals("one")) {
    it.remove();
  }
  else if(item.equals("three")) {
    it.remove();
  }
}

System.out.println("Latest someList: " + someList);

This is the safe way to remove items from List when you will still continue iterating over the someList.

In JavaScript, you may do

var someArray = ["two", "one", "three"];
for(var i = 0; i < someArray.length; i++) {
  if(someArray[i] == "one") {
    someArray.splice(i, 1); // #1
  }
  else if(someArray[i] == "three") {
    someArray.splice(i, 1); // #2
  }
}

Unfortunately, by doing this, you will get exception thrown.

By executing line #1, "one" is removed from someArray, and next if you still continue the for loop, you will get exception as someArray is modified, affecting the for loop execution.

The best way to remove item from a JavaScript array is to iterate the Array from last.

var someArray = ["two", "one", "three"];
for(var i = someArray.length - 1; i >= 0; i--) {
  if(someArray[i] == "one") {
    someArray.splice(i, 1); // #1
  }
  else if(someArray[i] == "three") {
    someArray.splice(i, 1); // #2
  }
}

This is the safe way to remove items from JavaScript Array.

Why this works? You may think same thing also applies to Java right? Yes you are right. How this works? Leave it for your back home reading.

Java tips on joining string with separator

This is Java tips on joining string with separator. Sometimes you have an Array or List and you want to join the String with separator. For example, an Array {“one”,”two”,”three”}, you want to make it as a String as “one,two,three”.

You can have several ways, here do two:

private static String join_1(String[] array, String separator) {
	String s = "";
	String comma = "";
	for(int i = 0; i < array.length; i++) {
		s = s + comma + array[i];
		comma = separator;
	}
	return s;
}

private static String join_2(String[] array, String separator) {
	String s = "";
	for(int i = 0; i < array.length; i++) {
		s = s + array[i] + separator;
	}
	return s.substring(0, s.length() - separator.length());
}

I will recommend first method. Here is my analysis.

Both code run in same speed. Test by putting 10000 elements of array.

First code will simply lesser memory consumption compared to second code. As String#substring will create another new copy of String with different offset.

Java Tips on Array / List / Set / For Each Loop

This is a basic Java Tips on when and how to use Array, List, Set, and for each loop.

When you have a set of data you want to store, you can use Array / List / Set.

Array is a fixed size structure, meant, when you initialise Array to be size of 10, then you cannot alter the size already.

To declare an Array, you type:


String[] someArray = new String[3];
someArray[0] = "one";
someArray[1] = "two";
someArray[2] = "three";

List is a variable size structure, meant, you can add and remove items without declare its size yet.

To declare a List, you type:


List someList = new ArrayList();
someList.add("one");
someList.add("two");
someList.add("three");

You may want to convert Array into List, you do


String[] someArray = new String[3];
List someList = Arrays.asList(someArray);

You may want to convert List back to an Array, you do


List someList = new ArrayList();
String[] someArray = someList.toArray();

Set is an unique, non repeated version of List. For example, using List, you can store [1,2,3,2,1], as 2 repeated 2 times. But, Set, you always cannot repeat the items.

The most common implementation is HashSet, you do


Set someSet = new HashSet();
someSet.add("one");
someSet.add("two");
someSet.add("three");
someSet.add("one");

Note, in the output, you only can find [“one”, “two”, “three”]

And you may not see “one”,”two”,”three” in insertion order. Actually, Java will hash each item, by converting the String into a hash key, then store inside the HashSet, so you may see “two”, “one”, “three” but not “one”, “two”, “three”.

If you want the Set in insertion order, you should use LinkedHashSet.


Set someSet = new LinkedHashSet();
someSet.add("one");
someSet.add("two");
someSet.add("three");
someSet.add("one");

Then you will see “one”, “two”, “three”.

If you want the Set in ordered, you can use TreeSet. Everytime you insert an item, it will auto sort.


Set someSet = new TreeSet();
someSet.add("one");
someSet.add("two");
someSet.add("three");
someSet.add("one");

The output will be “one”, “three”, “two”. Or more better example,


Set someSet = new TreeSet();
someSet.add(3);
someSet.add(2);
someSet.add(1);
someSet.add(3);

The output will be 1,2,3.

To iterate the array, list, set, you can use for each loop construct.

OK, normally, you may already know, something like this


String[] someArray = new String[3];
for(int i = 0; i < someArray.length; i++) { someArray[i] }

You can do this:


String[] someArray = new String[3];
for(String item : someArray) {
item
}

This is same applies to List and Set.

For example:


List someList = new ArrayList();
for(String item : someList) {
item
}

Sometimes, good to use Array, sometimes, good to use List / Set.

If using List and Set, you can do something like add(), remove(), contains().

For example, if you want to filter something, you can use contains(), you can check if the List “contains” the item you want to search.


someList.contains("some thing");

Finally, you can bookmark my blog to follow up more Java Tips posted in future.