Reputation: 227
I am trying to update a file using Java with new data. Let 's say I have a txt file where I have saved the following data:
id grade
3498 8
2345 9
5444 7
2222 5
So I am trying to update the grade, depending the id the user has typed, but the new (updated) file has the type that follows:
id grade3498 62345 95444 72222 5
and so on....
I can t find the reason why this is not working, I guessed it has something to do with not adding a new line while re-writing the data, but even if I add new line character ("\n") in outobj.write(fileContent.toString()); nothing changes.
Here is a snippet of my code :
public String check(int num) throws RemoteException
{
String textinLine;
String texttoEdit;
File file=new File ("c:\\students.txt");
FileInputStream stream = null;
DataInputStream in =null;
BufferedReader br = null;
try
{
stream = new FileInputStream(file);
in =new DataInputStream(stream);
br = new BufferedReader(new InputStreamReader(in));
StringBuilder fileContent = new StringBuilder();
if ((num>0) && (num<6001))
{
while ((textinLine=br.readLine())!=null)
{
texttoEdit=Integer.toString(num);
System.out.println(textinLine);
String[] parts = textinLine.split(" ");
if (parts.length>0)
{
if (parts[0].equals(texttoEdit))
{
int value = Integer.parseInt(parts[1]);
value-=2;
String edit=Integer.toString(value);
String newLine = "\n"+parts[0]+" "+edit+"\n";
msg="You can pass2";
fileContent.append(newLine);
fileContent.append("\n"); }
else
{
fileContent.append(textinLine);
fileContent.append("\n");
}
}
}
}
in.close();
FileWriter fstream = new FileWriter(file);
BufferedWriter outobj = new BufferedWriter(fstream);
outobj.write(fileContent.toString());
outobj.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Finally, let me say that the new file is rightly edited, which means that if the user enters the id 3498, the grade value would change to 8-2=6, but the new file will be in a single line, as I explained before.
Upvotes: 0
Views: 112
Reputation: 328568
On some OS (typically Windows) you need to use \r\n
for a new line. Even better, you can use:
String newLine = System.getProperty("line.separator");
for the line separator which will adjust depending on the platform it is run on.
Upvotes: 6