从.txt文件中读取字符串,然后将其转换为整数

时间:2016-05-15 07:59:06

标签: java

我正在尝试从文本文件中读取一些数据,其格式为:

10
1
s
q

这是代码:

public static void main(String[] args) {

        String line = null;

        int[] b= new int[10];
        int i = 0;

        try {
            BufferedReader bf = new BufferedReader(new FileReader("C:\\myFile.txt"));

            while ((line = bf.readLine()) != null) {

                b[i] = Integer.parseInt(line);
                i++;

            }

        } catch (IOException e) {
            System.out.println(e.getMessage());

        }
}

b[i] = Integer.parseInt(line);可以轻松读取文件中的第一行' 10'同样适用于第二行,即' 1'但对于第三线的#39;编译器给我以下错误

Exception in thread "main" java.lang.NumberFormatException: For input string: "s"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at test.Main.main(Main.java:41)

我需要转换String' s'和' H'到一个整数值,然后存储到整数类型的数组b中。

3 个答案:

答案 0 :(得分:4)

首先检查字符串是否包含字母或数字

if(line.matches("[a-zA-Z]+"))
    int a=(int)line.charAt(0);

else if(line.matches("[0-9]+"))
    int a=Integer.parseInt(line);

答案 1 :(得分:0)

如果你只有一个角色,这应该有效:

char c = b[i].charAt(0);
int x = c - 48;

答案 2 :(得分:0)

您可以将文本文件转换为字节数组,然后将此数组转换为int数组

public static void Do()
{

    try {
        InputStream in;
        in = new FileInputStream("a.txt");
        byte[] array = new byte[in.available()];
        in.read(array);
        int[] array2 = new int[array.length];
        for (int i = 0 ; i<array.length ; i++)
        {
            array2[i] = array[i];
            System.out.println(array2[i]+"");
        }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}

,输出就像这样

  

13   10   99   13   10   100   13   10   100   102   104   102   103   104   103   102   104

取决于您的文本文件字符。 a.txt中的数据是(a b C d dfhfghgfh )

但是对我来说,我会给每个char一个整数值,然后使用if statment将char转换为int