java - 从文本文件 java 中删除单个和多个空格,但不应合并文本文件中的所有行
问题描述
考虑到 txt 文件中有 n 行,例如 4 行。
从文件输入:
ABCDE
FGHIJK
LMNOP
QRST
预期的输出文件:
ABCDE
FGHIJK
LMNOP
QRST
我设法产生的输出是:
ABCDEFGHIJKLMNOPQRST
预期的输出应如下所示,单词之间或行之间没有任何空格。
解决方案
首先,根据您的问题,如果您可以逐行阅读,那将是最有益的。幸运的是,使用 Java-8 的 Streams 实现,您可以做到这一点!
该方法会将文件的每一行作为String
, 添加到ArrayList<String>
.
static ArrayList<String> readFileText (String filename){
//ArrayList to hold all the lines
ArrayList<String> lines = null;
//Get lines of text (Strings) as a stream
try (Stream<String> stream = Files.lines(Paths.get(filename))){
// convert stream to a List-type object
lines = (ArrayList<String>)stream.collect(Collectors.toList());
}
catch (IOException ioe){
System.out.println("\nCould not read lines of text from the file.");
}
catch (SecurityException se){
System.out.println("Could not read the file provided." +
"Please check if you have permission to access it.");
}
return lines;
}
通过使用上述方法,您将设法将文本文件中的每一行添加为一个数组列表String
,但我们现在仍然必须从每个字符串中删除空格。
因此,一种非常简单的方法是使用以下方法编写输出文件:
static void writeFileText (String filename, ArrayList<String> linesOfText){
// Specify file location and name
Path file = Paths.get(filename);
// StringBuilder will be used to create ONE string of text
StringBuilder sb = new StringBuilder();
// Iterate over the list of strings and append them
// to string-builder with a 'new line' carriage return.
for( String line : linesOfText){
line.replaceAll(" ", ""); // Replace all whitespace with empty string
sb.append(line).append("\n");
}
// Get all bytes of produced string and instantly write them to the file.
byte[] bytes = sb.toString().getBytes();
// Write to file
try{
Files.write(file, bytes);
}
catch(IOException ioe){
System.out.println("\nCould not write to file \""+filename+"\".);
}
}
那么您的主要方法将只有 2 行长(考虑到您只是解决您发布的问题的方法,仅此而已):
public static void main(String[] args){
ArrayList<String> lines = Class.readFileText("input.txt");
Class.writeFileText("output.txt", lines);
}
在这里,Class是指静态方法所在的类名。
上述方法取自此GitHub 存储库。
推荐阅读
- python - 检查使用 Selenium 每天更改的复选框的值
- python - Flask_SQLAlchemy,db.create_all() 在通过服务类导入时无法“看到”我的表
- android - 像其他流行的应用程序一样在 dallery 和其中的图像/视频中显示应用程序文件夹
- rust - 货物运行抛出openssl错误并且无法编译
- angular - 我使用 angular 11 开了一张发票,但我无法计算总金额和总金额
- python - TypeError:预期的 str、bytes 或 os.PathLike 对象,而不是 Streamlit Web 应用程序中的 PngImageFile
- php - 使用 PHP foreach 循环在许多 html div 标签中显示数据
- asp.net-core - 尽管配置遵循文档,为什么 CORS 会阻止我在 Bolero (F# Blazor) 中的获取?
- angular - 其他函数中元素的角度刷新 validateFn
- python - 需要帮助使所得税计算器的代码在 Python 上更高效