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?
Asked
Active
Viewed 636 times
1 Answers
2
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());
}
}

user11809641
- 815
- 1
- 11
- 22
-
1And String file is the url? – TheAlexGamer Aug 13 '19 at 07:46
-
1`String file` is the path. If you are already reading the file as you mention above, you should already have the path. If not, you can get the path of a file with `File.getAbsolutePath()` – user11809641 Aug 13 '19 at 07:52
-
the .txt file is hosted on awardspace, a free hosting service on my domain, and the java file is on my pc. I managed to read the file, and it prints me the correct content, but i cannot write to it. I tried URLConnection and all kind of writing methods, nothing works. – TheAlexGamer Aug 13 '19 at 12:23