Java File Splitting: Read and Split Files by Lines
In Java, you can use the BufferedReader class to read a file line by line and use the split() method of String to split each line’s content. Here is an example code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split("\\s+"); // 使用空格拆分每一行的内容
for (String part : parts) {
System.out.println(part);
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the code above, we first create a BufferedReader object to read the file “file.txt”, and then use a while loop to read the contents of the file line by line. In each line, we use the split(“\s+”) method to split the content of each line using a space as a delimiter, and store the split results in a String array. Finally, we iterate through this array and print each part.