我正在尝试使用Java使用新数据更新文件。假设我有一个txt文件,其中保存了以下数据:
id grade
3498 8
2345 9
5444 7
2222 5因此,我正在尝试更新成绩,具体取决于用户输入的id,但新的(更新后的)文件的类型如下:
id grade3498 62345 95444 72222 5以此类推...
我找不到这不起作用的原因,我猜这与重写数据时没有添加新行有关,但即使我在outobj.write(fileContent.toString())中添加新行字符("\n"),也没有什么变化。
下面是我的代码片段:
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();
}最后,假设新文件被正确编辑,这意味着如果用户输入id3498,等级值将更改为8-2=6,但新文件将在一行中,正如我前面解释的那样。
发布于 2012-12-03 18:16:57
在一些操作系统(通常是Windows)上,您需要使用\r\n来创建新行。更好的是,你可以使用:
String newLine = System.getProperty("line.separator");对于行分隔符,它将根据运行它的平台进行调整。
https://stackoverflow.com/questions/13681118
复制相似问题