我想从文本文件中删除特定行。我发现了那条线,但接下来要做什么? 有什么想法吗?
答案 0 :(得分:5)
删除线条毫无魔力。
答案 1 :(得分:4)
从流中读取文件并将其写入另一个流并跳过要删除的行
答案 2 :(得分:2)
尝试阅读文件:
public static String readAllText(String filename) throws Exception {
StringBuilder sb = new StringBuilder();
Files.lines(Paths.get(filename)).forEach(sb::append);
return sb.toString();
}
然后从特定字符中拆分文本(对于新行" \ n")
private String changeFile(){
String file = readAllText("file1.txt");
String[] arr = file.split("\n"); // every arr items is a line now.
StringBuilder sb = new StringBuilder();
for(String s : arr)
{
if(s.contains("characterfromlinewillbedeleted"))
continue;
sb.append(s); //If you want to split with new lines you can use sb.append(s + "\n");
}
return sb.toString(); //new file that does not contains that lines.
}
然后将此文件的字符串写入新文件:
public static void writeAllText(String text, String fileout) {
try {
PrintWriter pw = new PrintWriter(fileout);
pw.print(text);
pw.close();
} catch (Exception e) {
//handle exception here
}
}
writeAllText(changeFile(),"newfilename.txt");
答案 3 :(得分:1)
无法直接在文件中删除文本行。我们必须将文件读入内存,删除文本行并重写已编辑的内容。
答案 4 :(得分:1)
试试这段代码。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class Solution {
public static void main(String[] args) throws FileNotFoundException, IOException{
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "bbb";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
}
答案 5 :(得分:0)
也许搜索方法会做你想要的,即“搜索”方法将字符串作为参数并将其搜索到文件中并替换包含该字符串的行。
PS:
public static void search (String s)
{
String buffer = "";
try {
Scanner scan = new Scanner (new File ("filename.txt"));
while (scan.hasNext())
{
buffer = scan.nextLine();
String [] splittedLine = buffer.split(" ");
if (splittedLine[0].equals(s))
{
buffer = "";
}
else
{
//print some message that tells you that the string not found
}
}
scan.close();
} catch (FileNotFoundException e) {
System.out.println("An error occured while searching in file!");
}
}