How can we iterate through a TXT file in Java to retrieve data?
You can use Java’s IO operations to traverse a TXT file and retrieve data. Here is a simple example code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadTXTFile {
public static void main(String[] args) {
String fileName = "data.txt";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
// 在这里处理每一行的数据
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the example above, we used the BufferedReader class to read data line by line. You need to replace the fileName variable with the actual path to your TXT file. Within the while loop, you can process each line of data as needed, such as storing it in an array or collection, or performing other operations on it.
Please note that the above examples use the try-with-resources statement, which automatically closes file resources. This is a recommended practice to ensure proper resource release. If you are using an older version of Java, you can use the traditional try-catch-finally statement to close file resources.