1
package javaapplication33;

import java.io.File;
import java.io.IOException;


public class JavaApplication33 {

public static void main(String[] args) throws IOException{


    File happyFile = new File("/happy.txt");
    if (happyFile.exists() == false) {
        happyFile.createNewFile();
        System.out.println("the file is created");
    } else {
        System.out.println("tHE FILE ALREADY EXSISTED   ");
     }
   }
 }

这是我的错误:

Exception in thread "main" java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:883)
at javaapplication33.JavaApplication33.main(JavaApplication33.java:14)

Java 结果:1

  • 我试过 C:// & C:/ 还是不行*
4

2 回答 2

2

如果您需要写入 Windows 中的特定路径,则需要使用带引号的反斜杠:

 File happyFile = new File("c:\\mydir\\happy.txt");

要使代码通用,您可以使用系统属性中的路径分隔符和主目录。

于 2013-07-06T20:09:10.620 回答
2

我认为“/happy.txt”不是有效的 Windows 文件路径。尝试一条始终有效的路径

import java.io.File;
import java.io.IOException;

public class WriteToDisk {
    public static void main(String[] args) throws IOException {
        String tempDir = System.getProperty("java.io.tempdir");
        String separator = File.pathSeparator;
        File happyFile = new File(tempDir + separator + "happy.txt");
        if (!happyFile.exists()) {
            happyFile.createNewFile();
            System.out.println("the file is created");
        }
        else {
            System.out.println("tHE FILE ALREADY EXISTED");
        }
    }
}

这将第一次打印“文件已创建”,然后在任何后续时间打印“文件已存在”。

于 2013-07-06T20:09:51.653 回答