0

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<>();

    try{
            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) {

                    }
                    br.close();
                    fr.close(); 
                }
            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 :

Abdellah OUMGHAR
  • 3,627
  • 1
  • 11
  • 16

2 Answers2

1

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) {
        al.add(line.split("\\s+"));
    }
} catch (IOException exception) {
    System.out.println("Exception: " + exception.getMessage());
    exception.printStackTrace();
}

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

String[][] array = al.toArray(new String[][] {});
System.out.println(Arrays.deepToString(array));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

I am just obsessed by the beauty of Java 8 and it's Streams.

Path p = Paths.get(System.getProperty("user.home"),"Desktop","itemsset.txt");
String [][] twoDee = Files.lines(p)
    .map((line)->line.trim().split("\\s+"))
    .toArray(String[][]::new);
System.out.println(Arrays.deepToString(twoDee));

Similar situations to be found:

Additional Research - java: convert a list of array into an array of array

Community
  • 1
  • 1
YoYo
  • 9,157
  • 8
  • 57
  • 74