我想从文本文件中删除特定的一行。我找到了那一行,但接下来该怎么做呢?有什么想法吗?
从流中读取文件并将其写入另一个流中,跳过您想要删除的行。
删除行并没有什么魔法。
试一试这段代码。
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);
}
}
public static String readAllText(String filename) throws Exception {
StringBuilder sb = new StringBuilder();
Files.lines(Paths.get(filename)).forEach(sb::append);
return sb.toString();
}
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");
直接在文件中删除文本行是不可能的。我们需要将文件读入内存,删除文本行并重新编写编辑后的内容。
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!");
}
}
.new
来创建一个新文件。你也可以使用File.rename()
来重命名它。 - Peter Lawrey