java 替换文本,Java替换文本文件中的行

这篇博客介绍了一个Java方法,用于读取文本文件并替换其中特定行的内容,而不是整个文件。方法通过BufferedReader读取文件,然后使用StringBuffer更新字符串,根据条件替换目标行,最后将更新后的字符串写回文件,实现了对文件中某一行的精确替换。
摘要由CSDN通过智能技术生成

How do I replace a line of text found within a text file?

I have a string such as:

Do the dishes0

And I want to update it with:

Do the dishes1

(and vise versa)

How do I accomplish this?

ActionListener al = new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

JCheckBox checkbox = (JCheckBox) e.getSource();

if (checkbox.isSelected()) {

System.out.println("Selected");

String s = checkbox.getText();

replaceSelected(s, "1");

} else {

System.out.println("Deselected");

String s = checkbox.getText();

replaceSelected(s, "0");

}

}

};

public static void replaceSelected(String replaceWith, String type) {

}

By the way, I want to replace ONLY the line that was read. NOT the entire file.

解决方案

Tested and works

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"));

String line;

StringBuffer inputBuffer = new StringBuffer();

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

inputBuffer.append(line);

inputBuffer.append('\n');

}

String inputStr = inputBuffer.toString();

file.close();

System.out.println(inputStr); // check that it's inputted right

// this if structure determines whether or not to replace "0" or "1"

if (Integer.parseInt(type) == 0) {

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

}

else if (Integer.parseInt(type) == 1) {

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

}

// check if the new input is right

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");

}

Original Text File Content:

Do the dishes0

Feed the dog0

Cleaned my room1

Output:

Do the dishes0

Feed the dog0

Cleaned my room1

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

Do the dishes1

Feed the dog0

Cleaned my room1

New text file content:

Do the dishes1

Feed the dog0

Cleaned my room1

And as a note, if the text file was:

Do the dishes1

Feed the dog0

Cleaned my room1

and you used the method replaceSelected("Do the dishes", "1");,

it would just not change the file.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值