我正在尝试读取文件内容并删除一些指定的字符串,但我仍然没有成功。我试过了this link too
但它不起作用,我也尝试使用ignorecase,在这种情况下我的整个文件都被删除了。 :(
我自己的代码就像
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(tempfile), charset)); BufferedWriter bw = new BufferedWriter(writer);
while((currentLine = reader.readLine()) != null)
{
//System.out.println(currentLine);
if (currentLine.equals(del))
currentLine = currentLine.replace(del, "");
writer.write(currentLine);
}
tempfile.renameTo(file);
答案 0 :(得分:0)
您的逻辑将仅在整行匹配时删除字符串。如果要匹配每行中字符串的一部分,请尝试使用字符串类中可用的匹配(或)子字符串方法
答案 1 :(得分:0)
您是否收到任何异常,或者只是新文件的所有内容与原始文件相同?
您应该关闭写入流,以便将其内容刷新到物理文件,然后尝试检查该文件。
答案 2 :(得分:0)
currentLine.equals(del)
你的意思是currentLine.matches(del)
currentLine.equals(del)
匹配整行,而currentLine.matches(del)
匹配currentLine的子字符串。
答案 3 :(得分:0)
你可以这样做
BufferedReader br = new BufferedReader(new FileReader("D:\\test.txt"));
List<String> lines=new ArrayList<>();
String currentLine = new String();
while ((currentLine = br.readLine()) != null) {
if (currentLine.contains("hi")) {
lines.add(currentLine.replace("hi", ""));
}else {
lines.add(currentLine);
}
}
BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\test.txt"));
for (String i:lines){
bw.write(i);
bw.newLine();
}
bw.close();
这是我的意见。
hi how are you?
I am fine.
again hi hi.
Out put
how are you?
I am fine.
again .
答案 4 :(得分:0)
您可以保留大部分原始代码,并避免将整个文件存储在List中(如果文件很大,可能会很糟糕)。这是一个你可以玩的单机:
import java.io.*;
public class StringRepl {
public void doReplace(String oldFileName, String newFileName) {
File oldFile = new File(oldFileName);
File tempFile = new File(newFileName);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(oldFile), "utf-8"));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "utf-8"));
BufferedWriter bw = new BufferedWriter(writer);
String currentLine;
String del = "hi";
while((currentLine = reader.readLine()) != null)
{
//System.out.println(currentLine);
if (currentLine.contains(del))
currentLine = currentLine.replace(del, "");
bw.write(currentLine);
bw.newLine();
}
bw.close();
reader.close();
writer.close();
//tempFile.renameTo(oldFile);
} catch (FileNotFoundException fnfe) {
System.out.print("No file found: " + oldFileName);
} catch (UnsupportedEncodingException uee) {
System.out.print("'utf-8' not supported");
} catch (IOException ioe) {
System.out.print("Error using file!");
ioe.printStackTrace();
}
}
public static void main(String[] args) {
StringRepl sr = new StringRepl();
sr.doReplace("o.txt","n.txt");
}
}
编译并运行:
javac StringRepl.java
java StringRepl
o.txt:
hi how are you?
I am fine.
again hi hi.
n.txt:
how are you?
I am fine.
again .