在java中构建后无法读取文件

时间:2015-04-28 20:21:58

标签: java file netbeans

嘿伙计们,我有这个程序来读取文件

public static String readFileAsString(String filename){
    BufferedReader reader;
    try {
        reader = new BufferedReader(new FileReader(filename));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null){
            sb.append(line + "\n");
        }
        reader.close();
        return sb.toString();
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "File Not Found","ERROR",JOptionPane.ERROR_MESSAGE);
    } catch (IOException ex) {  
        Logger.getLogger(tsst.class.getName()).log(Level.SEVERE, null, ex);
    }  
    return null;
  }

这是我的构造函数

public tsst() {
    initComponents();
    JOptionPane.showMessageDialog(null, readFileAsString("test.txt"),"Succes",JOptionPane.DEFAULT_OPTION);
}

并且文件在应用程序项目中如果我从Netbeans运行文件它的工作正常我得到了我需要但是如果我构建应用程序所以我得到了JAR文件并且我运行它我得到错误文件没找到 和写作中的相同

public static void writeFile(String canonicalFilename, String text){
  File file = new File (canonicalFilename);
  BufferedWriter out; 
      try {
         out = new BufferedWriter(new FileWriter(file));
         out.write(text);
         out.close();
     } catch (IOException ex) {
         Logger.getLogger(tsst.class.getName()).log(Level.SEVERE, null, ex);
     }
}

1 个答案:

答案 0 :(得分:1)

在readFileAsString方法中添加此行

System.out.println("Current Directory:"+ new File(".").getAbsolutePath());

这将告诉您应用程序的当前目录是什么。将test.txt文件放在同一目录中,您应该能够阅读它。我想象Netbeans(你知道文件是预期的)和运行Jar(可能是任何地方)之间的输出会有所不同。