NeSsMa OuNnOughi NeSsMa OuNnOughi - 1 year ago 85
Java Question

reading from .txt file into a 2d array

I have txt file all separated by a space, I know how to read in the file, but I don't know how to place the data into the array

this is the code :

public static void main(String[] args) throws IOException
ArrayList<String> list=new ArrayList<>();

File f = new File("C:\\Users\\Dash\\Desktop\\itemsset.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
String array[][] = null ;
try {
while ((line = br.readLine()) != null) {

catch (IOException exception) {
System.out.println("Erreur lors de la lecture :"+exception.getMessage());
catch (FileNotFoundException exception){
System.out.println("Le fichier n'a pas été trouvé");

Description below :

Answer Source

I have txt file all separated by a space

Read each line, and split it by white space. First, you can construct your file path using the user.home system property and relative paths. Something like,

File desktop = new File(System.getProperty("user.home"), "Desktop");
File f = new File(desktop, "itemsset.txt");

Then use a try-with-resources and read each line into a List<String[]> like

List<String[]> al = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
    String line;
    while ((line = br.readLine()) != null) {
} catch (IOException exception) {
    System.out.println("Exception: " + exception.getMessage());

Then you can convert your List<String[]> into a String[][] and display it with Arrays.deepToString(Object[]) like

String[][] array = al.toArray(new String[][] {});