如何将InputStream转换为int

这个问题在这里已经有了答案:

  • 如何在Java中将字符串转换为int? 30个答案

  • 如果这是你到目前为止:

    InputStream letturaEasy = getResources().openRawResource(R.raw.max_easy);
    

    然后,所有需要做的就是将其转换为字符串

    String result = getStringFromInputStream(letturaEasy);
    

    最后,以int

    int num = Integer.parseInt(result);
    

    顺便说一下, getStringFromInputStream()在这里被实现:

    private static String getStringFromInputStream(InputStream is) {
    
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
    
        String line;
        try {
    
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
    
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        return sb.toString();     
    }
    

    您可以使用BufferedReader从该文件读取行作为字符串。 Integer.parseInt会将它们解析为整数:

    try(BufferedReader reader = new BufferedReader(new InputStreamReader(letturaEasy, "UTF8")) ) {
        int n = Integer.parseInt(reader.readLine());
    }
    
    链接地址: http://www.djcxy.com/p/20919.html

    上一篇: How to convert InputStream to int

    下一篇: "String cannot be converted to int"