FileWriter, How to write on the same document [duplicate] - java

This question already has answers here:
Java FileWriter with append mode
(4 answers)
Closed 9 years ago.
I have created a Java Game and when the game finishes, a method is executed that tells the user to enter his his/her name then their score will save in playscores.txt document. This is working fine. However, i want the more than just one person's score in this document. I want it so everyone that plays the game name and score will be saved in this document. Would really appreciate some help.
This is my gameComplete Method code:
public void gameComplete() throws IOException {
String name = (String) JOptionPane.showInputDialog(
frame,
"Enter your name: ",
"Save Score",
JOptionPane.PLAIN_MESSAGE);
Score score = new Score(player.getScore(), name);
FileWriter fstream = new FileWriter("playerscores.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Name : " + score.getName() + System.getProperty( "line.separator" ) );
out.write("Score : " + score.getScore());
out.close();
}
I have tried different stuff, such as Objectoutputstream but unfortunately cannot figure out how to do it and was wondering if it is even possible. Furthermore, i would like to know what Class i should be using to get this done.

If you're happy to just append the new score to the end of the file, replace:
FileWriter fstream = new FileWriter("playerscores.txt");
with:
FileWriter fstream = new FileWriter("playerscores.txt", true);
If you can have more than one user playing at the same time, you'll need to use file locking too, to avoid race conditions when accessing the file.

In order to do it for more than one person, you should open the file in append mode.
FileWriter fstream = new FileWriter("playerscores.txt",true);
Syntax: public FileWriter(File file, boolean append)
Parameters:
file - a File object to write to
append - if true, then bytes will be written to the end of the file
rather than the beginning.
By default, the append parameter is false. So , earlier, you were over-writing the score of the previous player with the current one.

Firstly, if you want the file to be added to rather than wiped and written to each time then make sure you add the second argument of true to have it append the text.
You could use a CSV file to store the answers in columns and then read them out parsing the data by using commas.
FileWriter fileW = new FileWriter("playerscores.txt", true);
Hope that helps.

Related

Reading from a file in Java

I wrote a program that reads from a text file using Java. The file has 1 column with a lot of integer values and each value is being added to an array list. However, when I print the array list, between each number I am getting an empty entry. For example if in text file I have:
4
55
I am getting:
1 : ÿþ4 (Also I do not know what this weird character is)
2 :
3 : 555
Code:
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class ReadFile {
public static void main(String[] args) {
try
{
Scanner input = new Scanner("ReadingFile.txt");
File file = new File(input.nextLine());
input = new Scanner(file);
ArrayList numbers = new ArrayList();
int i=1;
while (input.hasNextLine()) {
String line = input.nextLine();;
numbers.add(line);
System.out.println(i + " : " + line);
i++;
}
input.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
I tried to avoid using the arraylist and just do :
System.out.println(i + " " + line);
however this problem is still there so I am guessing that it is not an ArrayList problem.
Provided your text file is actually a good text file, it could be a character encoding thing. You need to provide the correct character set to your scanner in its constructor. So change the line:
input = new Scanner(file);
Into something like:
String charset = "UTF-8";
input = new Scanner(file, charset);
Ofcourse, you need to figure out which character set your file is actually stored as and use that one. I do UTF-8 here only as an example.
OK, the problem is that you're actually reading binary from an excel file, hence the strange characters. If you want to read an excel file directly, then use a library such as JXL (http://jexcelapi.sourceforge.net/) - here's a good tutorial for using that API: http://www.vogella.com/tutorials/JavaExcel/article.html
Otherwise, you would want to save export your excel file to CSV format and read the file with your code.
weird chars should be writeUTF prefix or BOM. so, depends on how you write the file, reading method can be different.
if you write file with DataOutputStream and call writeUTF, then you should read the file with readUTF
if it is a simple text file that was written by a text program, like notepad++, I suggest call trim() function for every line.
Looks like your file is UTF-16. These two characters are the Byte order mark of UTF-16.
You must specify that when constructing your Scanner.
final Scanner scanner = new Scanner(file, "UTF-16");
If you don't have Notepad++ (text editor) download it. Open your generated text file using it.
Do find/Replace and populate the fields and check the settings by looking at the image below. then press Replace All. And then save your file. Your text file will be clean.

How do I print to a new line in java?

boolean valid = false;
String user = txtUser.getText();
String pass = txtPass.getText();
try {
PrintWriter writer = new PrintWriter("src/file");
writer.println("The line");
writer.println(user + "#" + pass);
JOptionPane.showMessageDialog(null,"Sign Up"complete",JOptionPane.INFORMATION_MESSAGE);
writer.close();
} catch(Exception e) {
}
I am making a sign up page and I already have made the login page. The # in the code is used to separate the username to the password. Everything works fine but the problem with this is that every time I sign up it replaces the sign up information I gave the previous time. So if I signed up the first time with the username "greg" and the password "877" it works fine but then if I go on program again and sign up another user with a different username and password, it replaces the first username and pass. I need it to go to new line after every time someone signs up.
Wrap your file with a FileWriter first:
PrintWriter writer = new PrintWriter(new FileWriter("src/file", true));
Here's the description for the constructor of FileWriter(String, boolean):
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
Parameters
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning
you are using public PrintWriter(File file) to write to the file
The javadoc says -
parameter specifies the file to use as the destination of this writer. If the file
exists then it will be truncated to zero size; otherwise, a new file will be created.
The output will be written to the file and is buffered.
So in your case you need to append text to the contents of the existing file so as Luiggi said FileWriter is your friend
FileWriter, a character stream to write characters to file. By default, it will
replace all the existing content with new content, however, when you specified a
true (boolean) value as the second argument in FileWriter constructor, it will keep
the existing content and append the new content in the end of the file.
try in this way
PrintWriter outputFile = new PrintWriter(new FileWriter("src/file", true));

how can i add data in to json file in java?

i want to add data inside of an existing json file..
this is my code:
JsonWriterWithGui(){
if(ae.getSource() == btn_submit){
String lname = (String)lbl_name.getText().toString();
String ladd = (String)lbl_add.getText().toString();
String lcontact = (String)lbl_contact.getText().toString();
FileWriter jsonFileWriter = new FileWriter( "E:\\"+tsave+".json");
jsonFileWriter.write(jsonObject.toJSONString());
jsonFileWriter.flush();
jsonFileWriter.close();
this code is already working. but I am trying to update a json file that already exists.
This is a bit of a guess because the problem you're having isn't entirely clear from the question, but if you're finding that your writes are overwriting instead of appending then try changing this line:
FileWriter jsonFileWriter = new FileWriter( "E:\\"+tsave+".json");
...to this:
FileWriter jsonFileWriter = new FileWriter("E:\\"+tsave+".json", true);
You see, FileWriter is backed by FileOutputStream, which takes a boolean argument saying whether new content should be appended or not. This boolean is false by default so if you want to append then you need to explicitly say so.

Java PrintWriter - Save File to Source Package in NetBenas

I am using the following java code in NetBeans to read and write to a file.
import java.io.*;
import java.util.*;
public class FileReadWrite {
StringTokenizer tokenizer;
BufferedReader inFile;
PrintWriter outFile;
File myFile;
private int[] highscores = new int[3];
public FileReadWrite() throws IOException, FileNotFoundException {
}
public int[] ReadFromSave() throws IOException, FileNotFoundException {
inFile = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/files/highscores.txt" )));
tokenizer = new StringTokenizer(inFile.readLine());
int i = 0;
while (tokenizer.hasMoreTokens()) {
highscores[i] = Integer.parseInt(tokenizer.nextToken());
i++;
}
inFile.close();
return highscores;
}
public void SaveFile(int score) throws IOException, FileNotFoundException {
if (score >= highscores[0]){
highscores[2] = highscores[1];
highscores[1] = highscores[0];
highscores[0] = score;
}
else if (score >= highscores[1]){
highscores[2] = highscores[1];
highscores[1] = score;
}
else if (score >= highscores[2]){
highscores[2] = score;
}
PrintWriter outFile = new PrintWriter(new FileWriter("/files/highscores.txt"));
String line = highscores[0] + " " + highscores[1] + " " + highscores[2];
outFile.println(line);
outFile.close();
}
}
I have coded a tetris program and want to save the highscores after each game. And when the user opens up the app next time they are shown the top 3 scores. The ReadFromSave() method started to work fine after I aded "getClass().getResourceAsStream". However I can't get the SaveFile() method working. I gives error "path/file not found". How should I use the PrintWriter in NetBeans so that it saves into the source packages and thus updating the jar. So when the app is fully closed and reopened it has the recent scores printed in. If this is not possible where can I save data so its not lost?
Thank you!!
If you want to be able to save the scores again, using getResourceAsStream isn't really a good idea - that's meant for resources which are bundled with the application, often within a jar file, and often read-only.
You might want to consider using the Java preferences API or work out some specific location for the file to use to store the high scores. Then just write to that file when saving, and read from it while loading. I wouldn't personally use PrintWriter (it swallows exceptions) or FileWriter (you can't specify the character encoding), but both should work. You just need to make sure you load the scores from the same file as you save it to. (It's not clear whether /files/highscores.txt is really an appropriate file to save to... do you have a /files directory? Were you expecting this to be relative to your application's working directory?)
(Also, it's a good idea to start following Java naming conventions, using camelCasing for method names... and use a try-with-resources statement to close writers, streams etc when you're finished with them, instead of manually calling close.)
You are mixing two things here. You are saving to an absolute path '/files/highscores.txt', but you are reading from the classpath, instead of the file system path. You'd have to choose one approach, but I'd stay away from absolute paths here.
However, a better approach might be to use the Preferences API, or Properties.load / store here. And if you're going to do IO operations, it might be better to look into Apache Commons IO, in which reading a file can be as trivial as doing FileUtils.readLines(file, "UTF-8");

Delete the content of csv file in Java

Every day I update a csv file using a FileWriter. When we step into a new month I have to delete the data from the previous month. My below code only updates a data in a csv file so, please help in deleting the previous month's data.
At least I need to know how to delete the data in csv file using FileWriter, so that I can manage to code for deleting previous month data.
private static void eventsUpdate(HttpServletRequest request,
HttpServletResponse response) {
String date=request.getParameter("date"); //getting from jsp page
String event=request.getParameter("event"); //getting from jsp page
File file = new File( "D:///events/events.csv");
if ( !file.exists() )
file.createNewFile();
FileWriter fw = new FileWriter(file,true);
BufferedWriter writer = new BufferedWriter( fw );
writer.write(date);
writer.write(",");
writer.write(event);
System.out.println("writing into excel");
writer.newLine();
writer.close();
fw.close();
}
Actually when you use the true argument in your FileWriter instantiation, you create a file writer object in append mode.
FileWriter fw = new FileWriter(file,false);
If you don't use the true option, the file will be overwritten by the new content. Therefore, I would suggest to follow this roadmap:
Read the file content as a whole, in a String
Remove the content you want to remove from the specific String
Overwrite the file
content using your new content in the specific String
Hope I helped!
I suggest you that you may create unique name file like march2014, january2013 instead of deleting it. Every month you need to read your target file which is named by your month strategy.
For ex:
When you reach april2014, create a new file april2014 etc. and read it for that month.

Categories

Resources