简体   繁体   中英

Writing a file using Java does not save the file in Mac OSx

I am developing a java application in which I need to save some data in a file. I tried to use different methods, however no file gets saved and I don't receive any errors. Here is my code for saving the file:

String filename = "/Users/name.txt";
    FileWriter fstream;

    try {
        fstream = new FileWriter(filename);
        BufferedWriter out = new BufferedWriter(fstream);
        out.write("My Name is Bobby Bob");
        out.newLine();                                  
        out.flush();
        out.close();
    } 
    catch (IOException e) {
        e.printStackTrace();          
    }

I tried even making the file myself but it remains empty.

It's unlikely that you can write directly to the Users folder through Java on Mac OSX.

Try this to make sure:

String filename = "/Users/name.txt";
FileWriter fstream;
try {
    File file = new File(filename);
    // checking if we can write this file
    System.out.println("Can write? " + file.canWrite());
    fstream = new FileWriter(file);
    BufferedWriter out = new BufferedWriter(fstream);
    out.write("My Name is Bobby Bob");
    out.newLine();
    out.flush();
    out.close();
} catch (IOException e) {
    e.printStackTrace();
}

Output expected:

Can write? false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM