Unexpected FileNotFoundException on FileWriter

后端 未结 2 1805
被撕碎了的回忆
被撕碎了的回忆 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
    }
    
    0 讨论(0)
  • 2021-01-26 16:37

    You can't use a tilde ~ in your path. If you want the user's home directory, you can get it from System.getProperty("user.home")

    0 讨论(0)
提交回复
热议问题