我有一个包含abc.txt的文件
hhjj
myhome _ dfdfdsfds fdsfds
dfdfdsfdsd fdsfdsf dfdfdsfdsdfdsfd
dfdsfds
dfdsfds _
hhhh j kkkk
myhome之后的字符可以是任何字符,可以是特殊字符,字母或数字。我需要找到myhome之后的字符,并删除中间的以字符结尾的行。在我的文件中,我在myhome之后用''表示为''。
输出应为
hhjj
hhhh j kkkk
我已经尝试过如何逐行读取文件
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadStringFromFileLineByLine {
public static void main(String[] args) {
try {
File file = new File("abc.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
谁能帮忙??
答案 0 :(得分:0)
结构
App.java
package main;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
public class App {
public static void main(String[] args)
throws FileNotFoundException, UnsupportedEncodingException {
App app = new App();
app.parseFile();
}
void parseFile() throws FileNotFoundException, UnsupportedEncodingException {
// Reading from package main
File file = new File(getClass().getResource("/main/abc.txt").getFile());
// If you want to read from HDD, for example :
// File file = new File("/home/user/abc.txt"); or File file = new File("c:\\abc.txt");
Scanner input = new Scanner(file);
StringBuilder sb = new StringBuilder();
while (input.hasNextLine()) {
sb.append(input.nextLine());
sb.append("\n");
}
input.close();
String text = sb.toString();
text = text
.replace(
text.substring(
text.indexOf("myhome _"),
text.lastIndexOf('_')+1
),
""
)
.replace("\n\n", "\n");
Path newFile = Paths.get("abc_new.txt");
Files.write(newFile, Arrays.asList(text.split("\n")), Charset.forName("UTF-8"));
}
}
新的书面文件将位于项目文件夹中。