首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java中优化I/O操作?

问在Java中优化I/O操作?
EN

Stack Overflow用户
提问于 2013-02-05 14:11:56
回答 3查看 113关注 0票数 0

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

代码语言:javascript
复制
14,15,16,17
13,16,15,14
15,17,12,13
...
...

我知道每一行总是有4列。

我必须读取这个文件,根据分隔符(这里是",")拆分行,并将每列的值写入相应的文件中,即如果列中的值是14,则必须将其转储/写入到14.txt中,如果是15,则将其写入15.txt中,依此类推。

以下是我到目前为止所做的工作:

代码语言:javascript
复制
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

因此,有没有更好的选择,使我不必打开和关闭之前已经打开的文件。

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

EN

回答 3

Stack Overflow用户

发布于 2013-02-05 14:17:40

像这样的东西应该是有效的:

代码语言:javascript
复制
Map <Integer, PrintWriter> filesMap = new HashMap<>();
...
if(!filesMap.containsKey(cols[i]))
{
  //add a new PrintWriter
} else
{
  //use the existing one
}
票数 2
EN

Stack Overflow用户

发布于 2013-02-05 14:21:28

试一试

代码语言:javascript
复制
    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
EN

Stack Overflow用户

发布于 2013-02-05 14:37:08

代码语言:javascript
复制
 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();
        }
    }
}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14701258

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档