简体   繁体   中英

Java - Reading a line from a file containing text and number

I'm just trying to do an exercise where I have to read a particular file called test.txt in the following format:

Sampletest 4

What I want to do is that I want to store the text part in one variable and the number in another. I am still a beginner so I had to google quite a bit to find something that would at-least work, here what I got so far.

    public static void main(String[] args) throws Exception{
    try {
        FileReader fr = new FileReader("test.txt");
        BufferedReader br = new BufferedReader(fr);

        String str;
        while((str = br.readLine()) != null) {
            System.out.println(str);
        }
        br.close();

    } catch(IOException e) {
        System.out.println("File not found");
    }

Use a Scanner , which makes reading your file way easier than DIY code:

try (Scanner scanner = new Scanner(new FileInputStream("test.txt"));) {
    while(scanner.hasNextLine()) {
        String name = scanner.next();
        int number = scanner.nextInt();
        scanner.nextLine(); // clears newlines from the buffer
        System.out.println(str + " and " + number);
    }
} catch(IOException e) {
    System.out.println("File not found");
}

Note the use of the try-with-resources syntax, which closes the scanner automatically when the try is exited, usable because Scanner implements Closeable .

You just need:

 String[] parts = str.split(" ");

And parts[0] is the text (sampletest) And parts[1] is the number 4

It seems like you are reading the whole file content (from test.txt file) line by line, so you need two separate List objects to store the numeric and non-numeric lines as shown below:

String str;
List<Integer> numericValues = new ArrayList<>();//stores numeric lines
List<String> nonNumericValues = new ArrayList<>();//stores non-numeric lines
while((str = br.readLine()) != null) {
    if(str.matches("\\d+")) {//check line is numeric
         numericValues.add(str);//store to numericList
    } else {
          nonNumericValues.add(str);//store to nonNumericValues List
    }
}

You can use java utilities Files#lines()

Then you can do something like this. Use String#split() to parse each line with a regular expression, in this example i use a comma.

public static void main(String[] args) throws IOException {
    try (Stream<String> lines = Files.lines(Paths.get("yourPath"))) {
        lines.map(Representation::new).forEach(System.out::println);
    }        
}

static class Representation{
    final String stringPart;
    final Integer intPart;

    Representation(String line){
        String[] splitted = line.split(","); 
        this.stringPart = splitted[0];
        this.intPart = Integer.parseInt(splitted[1]);
    }
}

If you are sure the format is always for each line in the file.

String str;
List<Integer> intvalues = new ArrayList<Integer>();
List<String>  charvalues = new ArrayList<String>();
try{
  BufferedReader br = new BufferedReader(new FileReader("test.txt"));
  while((str = br.readLine()) != null) {
   String[] parts = str.split(" ");
   charvalues.add(parts[0]);
   intvalues.add(new Integer(parts[0]));
 }
}catch(IOException ioer) {
 ioer.printStackTrace();
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM