I have a set of values ​​in a text file

1529666255304 123456789 128.158.234.15 1529666289305 123456799 123.148.214.19 ...... 

they are all String

how to write to the array only the first values ​​of t e

 1529666255304 1529666289305 ..... 

that's what i got

  String [] mass; try { BufferedReader br= new BufferedReader(new FileReader("C:file.txt")); String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { mass = sCurrentLine.trim().split("\\s+"); } } catch (IOException e) { e.printStackTrace(); } 

    2 answers 2

    Do the separation, check the number of elements and add the first:

     List<String> items = new ArrayList<>(); try { BufferedReader br= new BufferedReader(new FileReader("C:/file.txt")); String line; while ((line = br.readLine()) != null) { String[] parts = line.trim().split("\\s+"); if (parts.length > 0) { items.add(parts[0]); } } } catch (IOException e) { e.printStackTrace(); } System.out.println(items); 
    • why prints first comma? T e [, 1553609880, 1553609881, 1553609882, 1553609883, 1553609884, 1553609885, 1553609886, 1553609887, 1553609888, 1553609889] - Djoni
    • It looks like an empty element has been added ... check if you have a strange line above 1553609880 , you can still add a check: if (parts.length > 0 && !parts[0].isEmpty()) { or check the line line.trim() for empty line.trim() - gil9red am
    • thanks, &&! parts [0] .isEmpty () helped - Djoni

    With the help of streams

     String[] result = new BufferedReader(new FileReader("C:/file.txt")).lines() .map(s -> s.trim().split("\\s+")[0]) .toArray(String[]::new); 

    Using a container and then converting it to an array

     BufferedReader br = new BufferedReader(new FileReader("C:/file.txt")); String sCurrentLine; ArrayList<String> lines = new ArrayList<>(); while ((sCurrentLine = br.readLine()) != null) { lines.add(sCurrentLine.trim().split("\\s+")[0]); } String[] result = lines.toArray(new String[0]);