【问题标题】:Java create file if does not existJava 创建文件如果不存在
【发布时间】:2016-02-08 11:59:36
【问题描述】:

在我的函数中,我想读取一个文本文件。如果文件不存在,它将被创建。我想使用相对路径,所以如果我有 .jar,文件将在完全相同的目录中创建。我试过this。这是我的函数,变量fName 设置为test.txt

    private static String readFile(String fName) {
    String noDiacText;
    StringBuilder sb = new StringBuilder();
    try {
        File f = new File(fName, "UTF8");
        if(!f.exists()){
            f.getParentFile().mkdirs();
            f.createNewFile();
        }

        FileReader reader = new FileReader(fName);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fName), "UTF8"));

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);

        }
        reader.close();

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


    return sb.toString();
}

我在f.createNewFile(); 收到错误提示

java.io.IOException:  System cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
at main.zadanie3.readFile(zadanie3.java:92)

【问题讨论】:

  • 添加一个 println 或其他东西并调试路径的样子。你能不能说一下函数的哪一行抛出了异常。
  • 如果你使用 Java 7+,你应该考虑改用 java.nio.file
  • 为什么?空文件对你有什么好处?还有一个空字符串?抓住FileNotFoundException, 或者最好还是让它被扔掉。

标签: java file ioexception


【解决方案1】:

问题是

File f = new File(fName, "UTF8");

不将文件编码设置为 UTF8。相反,第二个参数是子路径,与编码无关;第一个是父路径。

所以你想要的实际上是:

File f = new File("C:\\Parent", "testfile.txt");

或者只是:

File f = new File(fullFilePathName);

没有第二个参数

【讨论】:

    【解决方案2】:

    使用 mkdirs() --plural-- 创建路径的所有缺失部分。

    File f = new File("/many/parts/path");
    f.mkdirs();
    

    请注意,'mkdir()' --singular-- 如果可能的话,只创建路径的列表部分。

    【讨论】:

      猜你喜欢
      • 2012-03-26
      • 2017-02-19
      • 2012-05-10
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      相关资源
      最近更新 更多