Java PrintWriter 写入将数据设置为.txt

标签 java iterator set printwriter

问题:如何使用 Java PrintWriter 递增集合并写入 .TXT

摘要:扫描指定文本文件并处理文本。然后将结果导出到报告 .txt。

这一切似乎都正常工作,直到我尝试使用 PrintWriter 为止。 然后事情就变得疯狂了。如果一切都保持代码中的原样,并且我打印到终端,它就可以工作。如果我使用 PrintWriter,它将创建文件,然后仅打印 tType“text2”的第二次迭代。我已经尝试了这里发布的许多不同的示例,但它们似乎都没有完全打印、根本不打印或出现错误。

文本文件输入示例:

123456  text1   175.00  001
234567  text2   195.00  001
345678  text1   175.00  007
456789  text3   160.00  005
987654  text4   90.00   006
876543  text3   160.00  007
765432  text2   195.00  011

所需输出示例:

text1
text2
text3
text4

当前正在使用 PrintWriter 输出到 .txt

text2

代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;


public class test {

  public static void main(String[] arg){  

     Set<String> tSet= new TreeSet<>();    
    Map<String, Double> idList = new TreeMap<String, Double >();

        //Get input File.
        Scanner console = new Scanner(System.in);
        System.out.println("Enter the full path to your file: ");

        //Error handling in try catch for file not found
        try {
            String inputFileName = console.next();

            //Scanner creation and varaibles
            File inputFile= new File(inputFileName);
            Scanner input = new Scanner(inputFile);




            //Input contents  number , type, price ,ID
            //Loop


            while (input.hasNext()) 
            {
                String Num = input.next(); 
                String tType = input.next();
                tType=tType.toUpperCase();
                tSet.add(tType);
                Double tPrice=Double.parseDouble(input.next());
                String tAgent = input.next();
        //add if record does not exist, else append to existing record
                if (idList.containsKey(tAgent)) {
                    idList.put(tAgent, idList.get(tAgent) + tPrice);
                } 
                else 
                {
                    idList.put(tAgent, tPrice);
                }

            }

            input.close();

        //catch for incorrect file name or no file found
        } catch (FileNotFoundException exception) {
            System.out.println("File not found!");
            System.exit(1);
        }



  //Create Set iterator
  Iterator iterator;
  iterator = tSet.iterator();

  while(iterator.hasNext()){

      try {
      PrintWriter report= new PrintWriter("txtx.txt");
      report.println(iterator.next()+ " ");
     // System.out.println(iterator.next()+ " ");
      report.flush();
// report.close();
      }



    catch (IOException e) {
        System.out.println("Error could not write to location");
    }   


  }


}
}

最佳答案

输出循环的每次迭代都会重新创建(覆盖)文件。来自 Oracle documentation

fileName - The name of the file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created.

不要在循环中创建 PrintWriter,而是在循环之前创建它。

//Create Set iterator
Iterator iterator;
iterator = tSet.iterator();

try
{
    PrintWriter report= new PrintWriter("txtx.txt");

    while(iterator.hasNext()){
        report.println(iterator.next()+ " ");
        report.flush();
    }

    report.close();
}
catch (IOException e) {
    System.out.println("Error could not write to location");
}   

关于Java PrintWriter 写入将数据设置为.txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24701901/

相关文章:

java - 显示输入字符串中的空格数?

c++ - 性能 - 使用迭代器或指针迭代 vector ?

java - 如何在java中一个接一个地遍历两个不同类型的泛型列表?

python - 过滤集合的最 Pythonic 方法是什么?

python - 将列表转换为集合会改变元素的顺序吗?

java - BeanDefinitionStoreException 运行服务器时无法读取候选组件类

java - 使用 JAXB 解码具有不同/动态名称的元素

java - 如何在我的应用程序中使用 android 日历?

c++ - vector::erase() 未按预期工作

python - 如果在 python 中成功,将元素添加到集合中会返回 true 吗?