如何替换文本文件中找到的文本行?
我有一个字符串,如:
Do the dishes0
我想用以下内容更新它:
Do the dishes1
(反之亦然)
我如何做到这一点?
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) {
}
顺便说一句,我想只替换读取的行。不是整个文件。
答案 0 :(得分:32)
在底部,我有一个替换文件中的行的通用解决方案。但首先,这是对手头具体问题的答案。助手功能:
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 清理我的房间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 lines
public 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.");
}
}
答案 1 :(得分:24)
从Java 7开始,这非常简单直观。
List<String> fileContent = new ArrayList<>(Files.readAllLines(FILE_PATH, StandardCharsets.UTF_8));
for (int i = 0; i < fileContent.size(); i++) {
if (fileContent.get(i).equals("old line")) {
fileContent.set(i, "new line");
break;
}
}
Files.write(FILE_PATH, fileContent, StandardCharsets.UTF_8);
基本上你将整个文件读到List
,编辑列表,最后将列表写回文件。
FILE_PATH
代表文件的Path
。
答案 2 :(得分:2)
如果替换长度不同:
如果替换长度相同:
这是你能得到的最好的,有你的问题的约束。但是,至少有问题的例子是替换相同长度的字符串,所以第二种方式应该有用。
另请注意:Java字符串是Unicode文本,而文本文件是带有某些编码的字节。如果编码是UTF8,并且您的文本不是Latin1(或普通的7位ASCII),则必须检查编码字节数组的长度,而不是Java字符串的长度。
答案 3 :(得分:2)
我打算回答这个问题。然后我看到它被标记为此问题的副本,在我编写代码之后,所以我将在此处发布我的解决方案。
请记住,您必须重新编写文本文件。首先,我读取整个文件,并将其存储在一个字符串中。然后我将每一行存储为字符串数组的索引,第一行=数组索引0.然后编辑与您要编辑的行对应的索引。完成此操作后,我将数组中的所有字符串连接成一个字符串。然后我将新字符串写入文件,该文件将旧内容写入。不要担心丢失旧内容,因为它已经通过编辑再次写入。下面是我使用的代码。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
public class ChangeLineInFile {
public void changeALineInATextFile(String fileName, String newLine, int lineNumber) {
String content = new String();
String editedContent = new String();
content = readFile(fileName);
editedContent = editLineInContent(content, newLine, lineNumber);
writeToFile(fileName, editedContent);
}
private static int numberOfLinesInFile(String content) {
int numberOfLines = 0;
int index = 0;
int lastIndex = 0;
lastIndex = content.length() - 1;
while (true) {
if (content.charAt(index) == '\n') {
numberOfLines++;
}
if (index == lastIndex) {
numberOfLines = numberOfLines + 1;
break;
}
index++;
}
return numberOfLines;
}
private static String[] turnFileIntoArrayOfStrings(String content, int lines) {
String[] array = new String[lines];
int index = 0;
int tempInt = 0;
int startIndext = 0;
int lastIndex = content.length() - 1;
while (true) {
if (content.charAt(index) == '\n') {
tempInt++;
String temp2 = new String();
for (int i = 0; i < index - startIndext; i++) {
temp2 += content.charAt(startIndext + i);
}
startIndext = index;
array[tempInt - 1] = temp2;
}
if (index == lastIndex) {
tempInt++;
String temp2 = new String();
for (int i = 0; i < index - startIndext + 1; i++) {
temp2 += content.charAt(startIndext + i);
}
array[tempInt - 1] = temp2;
break;
}
index++;
}
return array;
}
private static String editLineInContent(String content, String newLine, int line) {
int lineNumber = 0;
lineNumber = numberOfLinesInFile(content);
String[] lines = new String[lineNumber];
lines = turnFileIntoArrayOfStrings(content, lineNumber);
if (line != 1) {
lines[line - 1] = "\n" + newLine;
} else {
lines[line - 1] = newLine;
}
content = new String();
for (int i = 0; i < lineNumber; i++) {
content += lines[i];
}
return content;
}
private static void writeToFile(String file, String content) {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"))) {
writer.write(content);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String readFile(String filename) {
String content = null;
File file = new File(filename);
FileReader reader = null;
try {
reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return content;
}
}
上课。
{{1}}
答案 4 :(得分:1)
分享使用 Java Util Stream 的经验
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public static void replaceLine(String filePath, String originalLineText, String newLineText) {
Path path = Paths.get(filePath);
// Get all the lines
try (Stream<String> stream = Files.lines(path, StandardCharsets.UTF_8)) {
// Do the line replace
List<String> list = stream.map(line -> line.equals(originalLineText) ? newLineText : originalLineText)
.collect(Collectors.toList());
// Write the content back
Files.write(path, list, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.error("IOException for : " + path, e);
e.printStackTrace();
}
}
用法
replaceLine("test.txt", "Do the dishes0", "Do the dishes1");
答案 5 :(得分:1)
//Read the file data
BufferedReader file = new BufferedReader(new FileReader(filepath));
StringBuffer inputBuffer = new StringBuffer();
String line;
while ((line = file.readLine()) != null) {
inputBuffer.append(line);
inputBuffer.append('\n');
}
file.close();
String inputStr = inputBuffer.toString();
// logic to replace lines in the string (could use regex here to be generic)
inputStr = inputStr.replace(str, " ");
//'str' is the string need to update in this case it is updating with nothing
// write the new string with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream(filer);
fileOut.write(inputStr.getBytes());
fileOut.close();
答案 6 :(得分:0)
嗯,您需要使用JFileChooser获取文件,然后使用扫描仪和hasNext()函数读取文件的行
http://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html
一旦你这样做,你可以将行保存到变量中并操纵内容。
答案 7 :(得分:0)
就像我一样,如何替换字符串:) 第一个arg将是filename第二个目标字符串第三个是要替换的字符串而不是目标
package models;
import java.sql.*;
import oracle.sql.ARRAY;
import oracle.jdbc.OracleCallableStatement;
import oracle.sql.ArrayDescriptor;
public class TestDatabase {
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@address","user","pass");
// Convert your lists to arrays using #toArray( T[] )
String[] appoEvents = new String[4];
appoEvents[0] = "test";
appoEvents[1] = "internal";
appoEvents[2] = "123456";
appoEvents[3] = "2017-10-25 17:00:00";
appoEvents[4] = "2017-10-25 19:00:00";
CallableStatement st = con.prepareCall("{ call CORV5_WEB_STORE_APPOINTMENT( :appoEvents )}");
// Passing an array to the procedure -
((OracleCallableStatement) st).setARRAYAtName("test",appoEvents);
st.execute();
} catch(ClassNotFoundException | SQLException e) {
System.out.println(e);
}
}
}