Lets consider this scenario: I am reading a file, and then tweaking each line a bit and then storing the data in a new file. Now, I tried two ways to do it:
storing the data in a String and then writing it to the target file at the end like this:
InputStream ips = new FileInputStream(file); InputStreamReader ipsr = new InputStreamReader(ips); BufferedReader br = new BufferedReader(ipsr); PrintWriter desFile = new PrintWriter(targetFilePath); String data = ""; while ((line = br.readLine()) != null) { if (line.contains("_Stop_")) continue; String[] s = line.split(";"); String newLine = s[2]; for (int i = 3; i < s.length; i++) { newLine += "," + s[i]; } data+=newLine+"\n"; } desFile.write(data); desFile.close(); br.close();
directly using println() method for PrintWriter as below in the while loop:
while ((line = br.readLine()) != null) { if (line.contains("_Stop_")) continue; String[] s = line.split(";"); String newLine = s[2]; for (int i = 3; i < s.length; i++) { newLine += "," + s[i]; } desFile.println(newLine); } desFile.close(); br.close();
The 2nd process is way faster than the 1st one. Now, my question is what is happening so different in these two process that it is differing so much by execution time?