How to with simple input / output in Java

If you want to use Java for data analysis then you will find the input / output is very important. For example, for reading data from a file and analysing those data with a certain algorithm. After that you may want to print out the results into a new file and use it for making a fancy visualization.

This guide is on how to use IO Java API for making the operations of input / output mentioned before.

In the code bellow you can find an example of how to write content in a file, read it and then append some more data to existing content.

public class CreateFile {
	    public static void main( String[] args )
	    	try {
	    	  // create a new file
		      File file = new File("c:\\myfile.txt");
	          System.out.println("File created");
	          // write content to file
	          String content = "This is content to be writen in file";
	          FileWriter fw = new FileWriter(file.getAbsoluteFile());
			  BufferedWriter bw = new BufferedWriter(fw);
              System.out.println("content writen to file");
			  // read content from file
			  String line; 
			  BufferedReader br = new BufferedReader(new FileReader(file));
			  while((line = br.readLine())!= null){

			  //append new content to file 
			  String newcontent = "\nnew content for file";
	    		FileWriter fileWritter = new FileWriter(file.getAbsoluteFile(),true);
	    	    BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
	    	    System.out.println("new content writen in file");
	    	    System.out.println("lets read again the file");
	    	    BufferedReader br2 = new BufferedReader(new FileReader(file));
	    	    while((line = br2.readLine())!= null){
		} catch (Exception e) {

Is that simple in Java

If you enjoyed this article guide on how to with Java input / output please share


or follow data map on twitter..

Follow @datamap2t