【问题标题】:How to convert InputStream to int [duplicate]如何将 InputStream 转换为 int [重复]
【发布时间】:2015-03-01 19:33:54
【问题描述】:

我在 /raw 文件夹中有一个名为“max_easy.txt”的 txt 文件,在这个文件中写入了一个数字,在本例中为“0”...我想要一个 var 其具有 0 作为 Int 值,如何我要这样做吗?

我猜这行给了我一个字符串值,我该如何转换它?

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

【问题讨论】:

    标签: java string int


    【解决方案1】:

    如果这是你目前得到的:

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

    那么需要做的就是将其转换为字符串

    String result = getStringFromInputStream(letturaEasy);
    

    最后,int

    int num = Integer.parseInt(result);
    

    顺便说一句,getStringFromInputStream() 实现了here

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

    【讨论】:

    • getStringFromInputStream() 方法无法解析,所以我尝试了这个: String valore1 = getResources().getResourceEntryName(R.raw.max_easy); int num = Integer.parseInt(valore1); EasyTxt.setText(num); // 该行将显示在此文本视图中,但是一旦活动开始,应用程序就会停止工作,无论如何 Android Studio 没有给我任何错误......为什么? :(
    • 已更新答案,抱歉。
    • 太好了,现在应用程序运行良好!感谢您的帮助!
    【解决方案2】:

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

    try(BufferedReader reader = new BufferedReader(new InputStreamReader(letturaEasy, "UTF8")) ) {
        int n = Integer.parseInt(reader.readLine());
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-22
      • 2013-12-03
      • 1970-01-01
      • 2012-04-11
      • 2011-05-14
      • 2014-08-29
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多