Java-如何读取在同一行中包含Int和Strings的文本文件

问题描述 投票:0回答:5

如果文本文件包含

1 Apple
2 Banana
3 Orange
4 Carrot
5 Lemon
6 Lime
7 Mango 

如何读取文件以将第4行胡萝卜的内容存储到变量中,将第6行Lime的内容存储到单独的变量中?

    //Get data from file
    String fruit = "";
    String greenFruit = "";


    FileReader file = new FileReader("my/file/path.txt");
    BufferedReader reader = new BufferedReader(file);

    System.out.println(fruit);
    System.out.println(greenFruit);

最终结果是类似的东西>

"Fruit number 5 is a Lemon and Fruit Number 6 is a Lime"

如果文本文件包含1个Apple 2香蕉3橙4胡萝卜5柠檬6酸橙7芒果,如何读取该文件以存储内容,例如,将第4行胡萝卜变成变量,而将第6行石灰变成...。 >

java
5个回答
1
投票

尝试这样的事情:

String line = "";
String[] tokens;
int number;
String name;

while((line = reader.readLine()) != null)
{
    tokens = line.split(" ");

    // Use the following if you would rather split on whitespace for tab separated data
    // tokens = line.split("\\s+");

    number = Integer.parseInt(tokens[0]);
    name = tokens[1];

    System.out.println("Fruit number " + number + " is a " + name + "."
}

1
投票

我们可以使用Java NIO api来读取文件中的所有行,


0
投票
Fruit number 1 is a Apple and Fruit number 2 is a Banana and Fruit number 3 is a Orange and Fruit number 4 is a Carrot and Fruit number 5 is a Lemon and Fruit number 6 is a Lime and Fruit number 7 is a Mango

0
投票

Java 8样式:


0
投票

您可以使用// normal solution try (Stream<String> stream = Files.lines(Paths.get(fileName))) { stream.foreach(line -> { tokens = line.split(" "); number = Integer.parseInt(tokens[0]); name = tokens[1]; System.out.println("Fruit number " + number + " is a " + name + "." }); } catch (IOException e) { e.printStackTrace(); } // more OOP style public class Fruit { private int number; private String name; public Fruit(String line) { String[] line = line.split(" "); this.number = Integer.parseInt(line[0]); this.name = line[1]; } } List<Fruit> list = new ArrayList; try (Stream<String> stream = Files.lines(Paths.get(fileName))) { //1. convert all content to a object //2. convert it into a List list = stream .map(Fruit::new) .collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace(); } // then you can loop the list get what you want 阅读,并使用Scanner检查是否还有更多内容]

hasNext()
© www.soinside.com 2019 - 2024. All rights reserved.