To read a table from a text file in Java, you can use the BufferedReader
class, which reads text from a character-input stream, and the String.split
method, which splits a string into an array of substrings based on a delimiter.
Here is an example of how you can use the BufferedReader
class and the String.split
method to read a table from a text file in Java:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class TableReader { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new FileReader("table.txt")); String line; while ((line = reader.readLine()) != null) { String[] values = line.split(","); for (String value : values) { System.out.print(value + " "); } System.out.println(); } reader.close(); } }
In this example, the main
method creates a BufferedReader
object that reads from the file "table.txt". It then reads each line of the file using the readLine
method and splits it into an array of values using the split
method and a comma as the delimiter.
The values are then printed to the console using the System.out.print
method. The System.out.println
method is used to move to the next line after each row of the table is printed.
This code will read the table from the text file and print it to the console. You can modify the code to store the data in a data structure or perform other operations with it.
Keep in mind that this is just one way to read a table from a text file in Java. You can use different techniques and libraries to achieve the same result, such as using the Scanner
class or parsing the file manually using the String
and StringBuilder
classes.