简体   繁体   English

如何在 BufferReader 中同时使用 string 和 int?

[英]How to use both string and int in BufferReader?

I'm wondering if I can use BufferedReader with both string and integer, and what's wrong with my code?我想知道我是否可以将 BufferedReader 与字符串和整数一起使用,我的代码有什么问题?

import java.io.*;

public class Main {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        try {
            var writer = new BufferedWriter(new FileWriter("test.txt"));
            writer.write("hello");
            writer.write("\n welcome");
            for (int num : nums) {
                writer.write(num + "\n");
            }
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


        
        try {
            BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
            String line = reader.readLine();
            int num = Integer.parseInt(reader.readLine());
            while (line != null) {
                System.out.println(line);
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I want to read both int and string that have been written in the above method by JUST using BufferedReader我想通过使用 BufferedReader 读取在上述方法中写入的 int 和 string

You can try to check earlier, if given string is a number, eg:如果给定的字符串是数字,您可以尝试早点检查,例如:

private static boolean isNumeric(String str) {
    return str != null && str.matches("[0-9.]+");
}

and then, if isNumeric(line) is true, assign it as integer.然后,如果isNumeric(line)为真,则将其分配为整数。

First you are missing a few semicolons(;) on the line where you are creating the nums array and on the line you are writing the string '\n welcome'.首先,在创建 nums 数组的行和编写字符串 '\n welcome' 的行中缺少几个分号 (;)。

Secondly when writing to you file the first 2 lines are string values, so when you try to use parseInt on the second line it throws a NumberFormatException .其次,在写入文件时,前两行是字符串值,因此当您尝试在第二行使用parseInt时,它会抛出NumberFormatException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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