Java – Saving Text Files
Well yesterday we looked at loading text files in Java, today we will look at writing text files.
The code is very similar, but instead of FileInputStream, FileOutputStream will be used.
I don't expect this one to be as long as the loading text files. It is all the same principal so there is no need on going too far in depth.
Declare the IO package again (if its not already done):
This tutorial is assuming you already have something to save, I will be looping through an array already setup and save each element. (Was written earlier for my highscore system)
Start up the method:
public void saveFile(String fileName){ FileOutputStream out; PrintStream p;
Note, for this next part, thePlayers and theScore are both arrays. thePlayers is a String array while theScore is a int array.
Finish the method:
try { out = new FileOutputStream(fileName); p = new PrintStream(out); for (int i = 0; i < thePlayers.length; i ++){ p.println(thePlayers[i] + "," + theScores[i]); } p.close(); } catch (Exception e) { System.err.println ("Error writing to file"); } }
It uses something similar to System.out.print and println. It uses the PrintStream to print individual lines, by println or on the same line, through the use of print.
Hope this is helpful!



