【发布时间】:2015-04-10 09:05:59
【问题描述】:
我得到下面的代码来替换可以是 String 或 Int 的字段,但它没有按预期工作。我想做的是在文件 player.dat 中,字段是“用户名|密码|芯片数”我想根据用户名替换第三个字段,我使用字符串替换将旧字符串更改为新字符串字符串,但它不起作用,它只是在旧值旁边添加数字,并且我在文件中的所有数据都被原始数据逐行弄乱了。在这方面需要一些帮助
电流输出:
Username1|HashedPassword|200200Username2|HashedPassword2|300200Username3|HashedPassword3|300200
预期输出
Username1|HashedPassword|200
Username2|HashedPassword|300
Username3|HashedPassword|200
代码如下所示。
public class testcode {
public static void main(String[] args) {
new testcode().replace();
}
public void replace() {
String oldFileName = "players.dat";
String tmpFileName = "tempmod.dat";
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> player = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
Scanner read = new Scanner(System.in);
System.out.println("Please Enter Username");
String UserN = read.nextLine();
System.out.println("Please Enter Chips to Add");
String UserCadd = read.nextLine();
while ((line = br.readLine()) != null) {
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
int totalChips = Integer.parseInt(UserCadd) + Integer.parseInt(Chips);
if (Username.equals(UserN))
line = Username + "|" + Password + "|" +totalChips;
bw.write("\r\n"+line);
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
}
}
【问题讨论】:
-
所以你的实际问题是整数值的添加不起作用?查看此答案以了解如何将字符串转换为整数:stackoverflow.com/questions/5585779/… 您需要在添加操作之前执行此操作。
-
在其他软件如
notepad++..中打开.dat文件在某些编辑器中\n对.dat文件不起作用