Java - 从包含文本和数字的文件中读取一行

时间:2017-04-08 23:46:04

标签: java

我只是想做一个练习,我必须以下列格式阅读名为test.txt的特定文件:

Sampletest 4

我想要做的是我想将文本部分存储在一个变量中,将数字存储在另一个变量中。我仍然是一个初学者,所以我不得不谷歌找到一些至少可以工作的东西,这是我到目前为止所做的。

    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");
    }

5 个答案:

答案 0 :(得分:2)

使用Scanner,这使得阅读文件的方式比DIY代码更容易:

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");
}

请注意使用 try-with-resources 语法,该语法会在退出try时自动关闭扫描程序,因为Scanner实现了Closeable {{1}}

答案 1 :(得分:0)

你只需要:

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

部分[0]是文本(sampletest) 部分[1]是数字4

答案 2 :(得分:0)

您似乎正在逐行阅读整个文件内容(来自test.txt文件),因此您需要两个单独的List对象来存储数字和非 - 数字行如下所示:

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
    }
}

答案 3 :(得分:0)

您可以使用java实用程序Files#lines()

然后你可以做这样的事情。使用String#split()用正则表达式解析每一行,在本例中我使用逗号。

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]);
    }
}

答案 4 :(得分:0)

如果您确定格式始终是文件中的每一行。

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();
}
相关问题