要实现Java按行读取文件并以空格分割字符串的方法,可以使用以下步骤:
-
使用Java中的BufferedReader类读取文件中的每一行数据。
-
将每一行数据使用Java中的String类的split方法按照空格分割成字符串数组。
-
将分割后的字符串数组转换为每个元素带空格的字符串,并写入到输出文件中。
以下是两个示例:
示例一:
假设有input.txt文件内容为:
hello world
a b c d
1 2 3 4
实现按行读取文件并以空格分割字符串的代码如下:
import java.io.*;
public class FileReadAndSplit {
public static void main(String[] args) throws IOException {
String inputFile = "input.txt";
String outputFile = "output.txt";
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
String line = null;
while ((line = reader.readLine()) != null) {
String[] words = line.split("\\s+");
StringBuilder outputLine = new StringBuilder();
for (String word : words) {
outputLine.append(word).append(" ");
}
writer.write(outputLine.toString().trim());
writer.newLine();
}
reader.close();
writer.close();
}
}
运行结果为:
hello world
a b c d
1 2 3 4
示例二:
假设有input2.txt文件内容为:
apple banana carrot
dog cat tiger lion
实现按行读取文件并以空格分割字符串的代码如下:
import java.io.*;
public class FileReadAndSplit2 {
public static void main(String[] args) throws IOException {
String inputFile = "input2.txt";
String outputFile = "output2.txt";
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
String line = null;
while ((line = reader.readLine()) != null) {
String[] words = line.split("\\s+");
StringBuilder outputLine = new StringBuilder();
for (String word : words) {
outputLine.append(word).append(" ");
}
writer.write(outputLine.toString().trim());
writer.newLine();
}
reader.close();
writer.close();
}
}
运行结果为:
apple banana carrot
dog cat tiger lion
以上是Java按行读取文件并以空格分割字符串的完整攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java 按行读取文件按行写入文件并以空格分割字符串的方法 - Python技术站