I have a file "a.txt" which contains the following lines:
14,15,16,17 13,16,15,14 15,17,12,13 ... ... I know that each line will always have 4 columns.
I have to read this file and split the lines based on delimiter (here it is ",") and write the value of each column in its corresponding file i.e. if value in a column is 14 then it has to be dumped/wriiten in 14.txt, if its 15 then it will be written in 15.txt and so on.
Here is what I have done till now:
Map <Integer, String> filesMap = new HashMap<Integer, String>(); for(int i=0; i < 4; i++) { filesMap.put(i, i+".txt"); } File f = new File ("a.txt"); BufferedReader reader = new BufferedReader (new FileReader(f)); String line = null; String [] cols = {}; while((line=reader.readLine()) != null) { cols = line.split(","); for(int i=0;i<4;i++) { File f1 = new File (filesMap.get(cols[i])); PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(f1))); pw.println(cols[i]); pw.close(); } } So for line number 1 of file "a.txt", I will have to open, write and close files 14.txt,15.txt,16.txt and 17.txt
Again for line number 2, I have to again open,write and close files 14.txt,15.txt,16.txt and a new file 13.txt
So is there any better option in which I don't have to open and close the file which has already been opened earlier.
At the end of the complete operation I will close all the opened files.
14.txtwill contain a bunch of lines with the value14, etc? That makes no sense, and more importantly conflicts with your code, which seems to write all the first-column values into1.txt, second column values into2.txt, etc. Which is it?