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 :
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));
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.