因此,我创建了此方法,该方法最后显示了整行,因为我在转换和编辑后显示了数组。所以我的问题是我怎么知道将阵列覆盖到我从中抓取的同一行。在此先感谢,这是我的代码。
public void getData(String path, String accountNumber) {
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("Please Enter the Deposit amount That you would like to add.");
Scanner sn = new Scanner (System.in);
int add = sn.nextInt();
String str;
while ((str = br.readLine()) != null) {
if (str.contains(accountNumber)) {
String[] array = str.split(" ");
int old = Integer.parseInt(array[3]);
int Sum= old + add;
String Sumf = Integer.toString(Sum);
array[3] = Sumf;
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);}
break;
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
我正在使用字符串accountNumber来获取我需要的特定行。在获得该行之后,我将其更改为数组,同时使用str.split(“”);分割索引; 。之后,我知道我需要编辑索引号[3]。所以我这样做,然后将其放回阵列中。我需要做的最后一件事是立即将阵列放回原处。
最佳答案
您可以跟踪正在读取的文件中的输入,并使用修改后的版本将其写回。
public void getData(String path, String accountNumber) {
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("Please Enter the Deposit amount That you would like to add.");
Scanner sn = new Scanner (System.in);
int add = sn.nextInt();
String line; // current line
String input = ""; // overall input
while ((line = br.readLine()) != null) {
if (line.contains(accountNumber)) {
String[] array = line.split(" ");
int old = Integer.parseInt(array[3]);
int Sum= old + add;
String Sumf = Integer.toString(Sum);
array[3] = Sumf;
// rebuild the 'line' string with the modified value
line = "";
for (int i = 0; i < array.length; i++)
line+=array[i]+" ";
line = line.substring(0,line.length()-1); // remove the final space
}
// add the 'line' string to the overall input
input+=line+"\n";
}
// write the 'input' String with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream(path);
fileOut.write(input.getBytes());
fileOut.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
关于java - 覆盖Java txt文件中的一行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34562770/