Reputation: 3
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 :
Upvotes: 0
Views: 623
Reputation: 9415
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:
String []
to int []
conversion.Additional Research - java: convert a list of array into an array of array
Upvotes: 0
Reputation: 201517
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));
Upvotes: 1