[英]Overwriting a line in java txt file
因此,我创建了此方法,该方法最后显示了整行,因为我在转换和编辑后显示了数组。 所以我的问题是我怎么知道将阵列覆盖到我从中抓取的同一行。 在此先感谢,这是我的代码。
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);
}
}
这就是我如何理解您拥有文件的问题,您将逐行读取该文件,并进行一些更改并希望在同一位置再次写入。 创建一个新的临时文件,然后将内容写入临时文件。如果更改,则按原样写入更改后的结果。 最后将临时文件重命名为原始文件名
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.