gpt4 book ai didi

java - 覆盖java txt文件中的一行

转载 作者:行者123 更新时间:2023-11-30 07:41:50 24 4
gpt4 key购买 nike

所以我创建了这个方法,它最后显示整行,因为我在转换和编辑数组后显示数组。所以我的问题是我怎么知道将数组覆盖到我从中获取它的同一行。提前致谢,这是我的代码。

       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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com