java关于替换文本输出的讲解_Java替换文本文件中的行

在底部,我有一个替换文件中的行的一般解决方案。但首先,这是对手头具体问题的答案。辅助功能:public static void replaceSelected(String replaceWith, String type) {

try {

// input the file content to the StringBuffer "input"

BufferedReader file = new BufferedReader(new FileReader("notes.txt"));

StringBuffer inputBuffer = new StringBuffer();

String line;

while ((line = file.readLine()) != null) {

inputBuffer.append(line);

inputBuffer.append('\n');

}

file.close();

String inputStr = inputBuffer.toString();

System.out.println(inputStr); // display the original file for debugging

// logic to replace lines in the string (could use regex here to be generic)

if (type.equals("0")) {

inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0");

} else if (type.equals("1")) {

inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");

}

// display the new file for debugging

System.out.println("----------------------------------\n" + inputStr);

// write the new string with the replaced line OVER the same file

FileOutputStream fileOut = new FileOutputStream("notes.txt");

fileOut.write(inputStr.getBytes());

fileOut.close();

} catch (Exception e) {

System.out.println("Problem reading file.");

}}

然后叫它:public static void main(String[] args) {

replaceSelected("Do the dishes", "1");   }

原始文本文件内容:做菜0

喂狗0

清理我的房间1

输出:做菜0

喂狗0

清理我的房间1

----------------------------------

做菜1

喂狗0

清洗我的房间1

新文本文件内容:做菜1

喂狗0

清理我的房间1

并且作为注释,如果文本文件是:做菜1

喂狗0

清理我的房间1

并且您使用了该方法replaceSelected("Do the dishes", "1");,它只是不会更改文件。

由于这个问题非常具体,我将在这里为未来的读者添加一个更通用的解决方案(基于标题)。// read file one line at a time// replace line as you read the file and store updated lines in StringBuffer// overwrite the file with the new linespublic static void replaceLines() {

try {

// input the (modified) file content to the StringBuffer "input"

BufferedReader file = new BufferedReader(new FileReader("notes.txt"));

StringBuffer inputBuffer = new StringBuffer();

String line;

while ((line = file.readLine()) != null) {

line = ... // replace the line here

inputBuffer.append(line);

inputBuffer.append('\n');

}

file.close();

// write the new string with the replaced line OVER the same file

FileOutputStream fileOut = new FileOutputStream("notes.txt");

fileOut.write(inputBuffer.toString().getBytes());

fileOut.close();

} catch (Exception e) {

System.out.println("Problem reading file.");

}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值