Unexpected FileNotFoundException on FileWriter

后端 未结 2 1806
被撕碎了的回忆
被撕碎了的回忆 2021-01-26 16:10

I am attempting to create a simple text file that I will be writing to.

I receive the following error:

/Library/Java/Home/bin/java -Didea.launcher.port=7         


        
2条回答
  •  遥遥无期
    2021-01-26 16:24

    public static String filePath = "~//Desktop//";
    

    This will not work. In fact I am surprised that you say that it works on Windows.

    You probably meant for the '~' to mean your home directory...

    Except that it means this for the shell. Java has no idea what that is. What it will effectively try to do here is find a directory named '~' and an entry named Desktop in it.

    Use System.getProperty("user.home") to know what your home diretory it.

    And this is 2015, so don't use File. use java.nio.file instead:

    final Path path = Paths.get(System.getProperty("user.home"),
        "Desktop", "yourFileName");
    
    try (
        final BufferedWriter writer = Files.newBufferedWriter(path,
            StandardCharsets.UTF_8, StandardOpenOption.APPEND);
    ) {
        // use the writer here
    }
    

提交回复
热议问题