如何使用Java SE从txt文件中删除所有空格和空行?
输入:
输入:
qwe
qweqwe
qwe
qwe
输出:
qwe
qweqwe
qwe
qwe
谢谢!
qwe
qweqwe
qwe
qwe
输出:
qwe
qweqwe
qwe
qwe
谢谢!
FileReader fr = new FileReader("infile.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt");
String line;
while((line = br.readLine()) != null)
{
line = line.trim(); // remove leading and trailing whitespace
if (!line.equals("")) // don't write out blank lines
{
fw.write(line, 0, line.length());
}
}
fr.close();
fw.close();
...
Scanner scanner = new Scanner(new File("infile.txt"));
PrintStream out = new PrintStream(new File("outfile.txt"));
while(scanner.hasNextLine()){
String line = scanner.nextLine();
line = line.trim();
if(line.length() > 0)
out.println(line);
}
...
这是我第一次在这个网站上回答问题,请理解。经过很多搜索,我找到了适合我的方法。
FileReader fr = new FileReader("Input_Code.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("output_Code.txt");
String line;
while((line = br.readLine()) != null)
{
line = line.trim(); // remove leading and trailing whitespace
line=line.replaceAll("\\s+", " ").trim().concat("\n");
if (!line.equals("")) // don't write out blank lines
{
fw.write(line, 0, line.length());
}
}
fr.close();
fw.close();
我认为你只是想要一个正则表达式:
txt= txt.replaceAll("\\n\\s*\\n", "\n"); //remove empty lines
txt= txt.replaceAll("\\s*", ""); //remove whitespaces
去除每行的空格,不考虑空行和空值行:
String line = buffer.readLine();
while (line != null) {
line = removeSpaces(line);
//ignore empty lines
if (line.isEmpty()) return;
....code....
line = buffer.readLine();
}
public String removeSpaces (String arg)
{
Pattern whitespace = Pattern.compile("\\s");
Matcher matcher = whitespace.matcher(arg);
String result = "";
if (matcher.find()) {
result = matcher.replaceAll("");
}
return result;
}
package com.home.interview;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class RemoveInReadFile {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("Readme.txt"));
while(scanner.hasNext())
{
String line = scanner.next();
String lineAfterTrim = line.trim();
System.out.print(lineAfterTrim);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
public static void RemoveEmptyLines(String FilePath) throws IOException
{
File inputFile = new File(FilePath);
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
String inputFileReader;
ArrayList <String> DataArray = new ArrayList<String>();
while((inputFileReader=reader.readLine())!=null)
{
if(inputFileReader.length()==0)
{
continue;
}
DataArray.add(inputFileReader);
}
reader.close();
BufferedWriter bw = new BufferedWriter(new FileWriter(FilePath));
for(int i=0;i<DataArray.size();i++)
{
bw.write(DataArray.get(i));
bw.newLine();
bw.flush();
}
bw.close();
}