【问题标题】:File not found when i try to add to array list当我尝试添加到数组列表时找不到文件
【发布时间】:2021-10-05 18:33:11
【问题描述】:

我试图添加到数组列表,但 Eclipse 找不到 .txt 文件

public void readData(String filename) {
 
    try{
        File file = new File("C:\\Users\\Where Are Yew\\eclipse-workspace\\A2\\bin\\input.txt");
        FileReader filereader = new FileReader(file);
        BufferedReader br=new BufferedReader(filereader);
        String line;
        while(true) {
           line=br.readLine();
           if(line==null)
               break;
           String[] words=line.split("\\s");    

【问题讨论】:

  • 请分享您的整个代码,以及您收到的准确错误消息。
  • 嗨@akortex,感谢您的反馈,我的整个代码考虑了各种文件,您可以从这里下载:wetransfer.com/downloads/…,基本上我尝试运行一个显示学生结果的客户端,但是一个菜单中的选项“将学生数据添加到数组列表我似乎无法让 eclipse 读取 .txt 文件并将输出保存到 .csv 文件,我不确定代码有什么问题。

标签: java eclipse csv input output


【解决方案1】:
 String[] words = line.split("\\s+");

是您需要的,因为您的输入文件包含不规则间距。我强烈建议您使用制表符分隔的文件而不是空格分隔的文件,因为您的字段可以在需要的地方有空格

【讨论】:

  • 感谢@g00se 的输入和解释。
  • 很高兴。请点赞并接受答案
【解决方案2】:

玩这个方法更合适的方法可能是做这样的事情:

public void readData(String filename) {
    // 'Try With Resources' is use here to auto-close reader. 
    try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
        String line;
        while((line = br.readLine()) != null) {
            line = line.trim();  // Trim leading/trailing whitespaces, etc.
            // Skip past blank data lines
            if (line.isEmpty()) {
                continue;
            }
            // Do whatever you want to do with the read in data line.
            String[] words = line.split("\\s+");    
        }
    }
    /* Catch and display any IO Exception. If the file 
       can't be found then this will tell you. Perhaps
       you don't have permission to access it... it 
       would tell you that too. Don't ignore Exceptions. */
    catch (IOException ex) {
        Logger.getLogger("readData() Method Error!").log(Level.SEVERE, null, ex);
    }
}

【讨论】:

  • 感谢@DevilsHnd 的投入,今天学习一些关于 Java 的新知识。
猜你喜欢
  • 2022-12-18
  • 2023-04-09
  • 2016-09-27
  • 1970-01-01
  • 1970-01-01
  • 2012-06-01
  • 1970-01-01
  • 2018-08-28
  • 1970-01-01
相关资源
最近更新 更多