无法将文件从我的计算机本地目录加载到java程序

时间:2014-01-28 15:33:23

标签: java file sorting filenotfoundexception

我正在尝试编码排序字符串,从文本文件中获取输入。当我尝试为此程序指定文件时,会给我 FileNotFoundExcetion 我无法理解为什么? 即使我试图通过编写代码来获取文件路径,在屏幕中你可以看到路径是正确的但程序仍然给我错误

这是Screenshort  https://app.box.com/s/qytu1d9xlm0vcb6atz42

这是我的代码

public static void main(String[] args) throws FileNotFoundException, IOException {
  ArrayList<String> row1 = new ArrayList<>();
  FileWriter writer;

  try {

     String filename = "1.txt";
     String finalfile = "";
     String workingDir = System.getProperty("user.dir");

     String your_os = System.getProperty("os.name").toLowerCase();
     if (your_os.indexOf("win") >= 0) {
        finalfile = workingDir + "\\" + filename;
     } else if (your_os.indexOf("nix") >= 0 || your_os.indexOf("nux") >= 0) {
        finalfile = workingDir + "/" + filename;
     } else {
        finalfile = workingDir + "{others}" + filename;
     }

     System.out.println("Final filepath : " + finalfile);
     File file = new File(finalfile);

     if (file.createNewFile()) {
        System.out.println("Done");
     } else {
        System.out.println("File already exists!");
     }

  } catch (IOException e) {
     e.printStackTrace();
  }

  try (BufferedReader reader = new BufferedReader(new FileReader("finalfile"))) {
     String s;
     while ((s = reader.readLine()) != null) {
        row1.add(s);
     }
     Collections.sort(row1);
     writer = new FileWriter("output.txt");
     for (String s1 : row1) {
        writer.write(s1 + "\n");
     }
     reader.close();
     writer.close();
  } catch (Exception e) {
     System.out.print("Error : " + e);
  }

}

1 个答案:

答案 0 :(得分:1)

BufferedReader reader = new BufferedReader(new FileReader("finalfile"))) 

FileReader构造函数的参数被硬编码为&#34; finalfile&#34; - 您需要使用变量:

BufferedReader reader = new BufferedReader(new FileReader(finalfile))) 
                                                         ^^^^^^^^^^^

您还需要在第一个String finalfile = "";块之前移动try,否则在创建FileReader时它不在范围内。

此外,无需查询操作系统并手动设置目录路径分隔符。如果确实需要,请使用File.separator。否则,只需使用正斜杠 - this is working cross-platform

很高兴看到您正在使用try-with-resources - 但是,您应该这样做;只需在try语句中创建所有所需资源,然后就无需显式关闭它们:

try (BufferedReader reader = new BufferedReader(new FileReader(finalfile));
     FileWriter writer = new FileWriter("output.txt")) {

   ...

   // reader and writer will be auto-closed
} catch (IOException e) {
   System.out.print("Error : " + e);
}