简体   繁体   中英

How can i write to a .txt file stored on an online server in Java?

Heyy. I want to use java to write specific Strings to a .txt file which I hosted on my domain on awardspace. On awardspace, I edited the permissions so reading and writing is allowed. But for now I only figured out how to read from the file, and it works. Is there a way I can write to it?

You can use a simple method to append to a file. Just pass in the path of the file and the data to write to the file.

I normally use UTF-8 to ensure any special characters come out correctly.

public static void appendToFileUtf8(String file, String data) {
    try {
        FileOutputStream fout = new FileOutputStream(file, true);
        OutputStreamWriter outwrite = new OutputStreamWriter(fout, "UTF-8");
        outwrite.write(data);
        outwrite.close();
    } catch (IOException e) {
        throw new RuntimeException("Error writing to file: "+file+" "+e.getMessage());
    }
}

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