2013-02-05 33 views
0

我有一个文件“a.txt中”,其中包含以下几行:Java中优化的I/O操作?

14,15,16,17 
13,16,15,14 
15,17,12,13 
... 
... 

我知道每一行永远有4列。

我必须读取这个文件,并根据分隔符(这里是“,”)拆分行,并将每列的值写入相应的文件中,即如果列中的值是14,那么它必须被转储/ wriiten在14.txt中,如果它的15那么它将被写入15.txt等等。

这里是我做了什么至今:

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(); 
    } 
} 

所以对于文件“A.TXT”的1号线,我将不得不打开,写入和关闭文件14.txt,15.txt ,16.txt和17.txt

再次对2号线,我不得不再次打开,写入和关闭文件14.txt,15.txt,16.txt和一个新的文件13.txt

那么有没有更好的选择,我不必打开和关闭之前已打开的文件。

在完成操作后,我将关闭所有打开的文件。

+2

研究追加到文件,或只是在最后做一个大规模的打开/关闭。 –

+1

输入文件“a.txt”将有112500行。 因此,将完整的数据存储在内存中是一个明智的选择吗? – Tirthankar

+0

_“即如果列中的值是14,那么它必须在14.txt中被转储/读取......”_所以在这个结尾处,文件“14.txt”将包含一堆带有值'14'等?这是没有意义的,更重要的是与你的代码冲突,这似乎把所有的第一列值写入到'1.txt'中,将第二列值写入到'2.txt'中,等等。 –

回答

2

像这样的东西应该工作:

Map <Integer, PrintWriter> filesMap = new HashMap<>(); 
... 
if(!filesMap.containsKey(cols[i])) 
{ 
    //add a new PrintWriter 
} else 
{ 
    //use the existing one 
} 
+0

+1是的,我想回答..这将是有效的,因为你不会创建文件/作家每次..最后,你可以循环通过地图,并关闭所有 –

0

尝试

Set<String> s = new HashSet<>(); 
    Scanner sc = new Scanner(new File ("a.txt")).useDelimiter("[\n\r,]+"); 
    while(sc.hasNext()) { 
     String n = sc.next(); 
     if (s.add(n)) { 
      FileWriter w = new FileWriter(n + ".txt"); 
      w.write(n); 
      w.close(); 
     } 
    } 
    sc.close(); 
0
public static void main(String[] args) throws Exception { 
    FileReader fr = new FileReader("a.txt"); 
    BufferedReader reader = new BufferedReader(fr); 
    String line = ""; 

    while ((line = reader.readLine()) != null) { 
     String[] cols = line.split(","); 
     for (int i = 0; i < 4; i++) { 
      FileWriter fstream = new FileWriter(cols[i] + ".txt" , true);// true is for appending the data in the file. 
      BufferedWriter fbw = new BufferedWriter(fstream); 

      fbw.write(cols[i] + "\n"); 

      fbw.close(); 
     } 
    } 
} 

试试这个。我想你想这样做。