有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中io优化的I/O操作?

我有一个文件“a.txt”,其中包含以下行:

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

我知道每行总是有4列

我必须读取此文件,并根据分隔符(这里是“,”)拆分行,并将每列的值写入其相应的文件中,即如果列中的值为14,则必须在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。15岁。16岁。txt和17。txt

对于第2行,我必须再次打开、写入和关闭文件14。15岁。16岁。txt和一个新文件13。txt

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

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


共 (2) 个答案

  1. # 1 楼答案

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

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

  2. # 2 楼答案

    像这样的方法应该有用:

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