【问题标题】:the output vlaue isn't the sme as the value i have entered to a file when i enter 21 thw output of x =50? [duplicate]当我输入 x = 50 的 21 thw 输出时,输出值不是作为我输入到文件中的值的 sme? [复制]
【发布时间】:2018-03-11 15:13:17
【问题描述】:
package file;
import java.io.*;

public class x {
    public static void main(String[] args) {
        try {
            FileWriter fs = new FileWriter("ahmed.txt");
            fs.write("21");

            fs.close();
            FileReader fr = new FileReader("ahmed.txt");
            //String x = Integer.toString(fr.read());
            int x = fr.read();
            System.out.println(x);
            fr.close();
        } catch (Exception ex) {                 
          ex.printStackTrace();
        }
   }
}

当输入为 20 和 21 时 x 的输出值为 50 我该怎么办 把输入变成输出

【问题讨论】:

  • 听起来像是在读取字节,因为 2 的 ASCII 值是 50
  • 嗯,它正在读取单个字符。这可能包含多个字节。但它肯定不会读取多个字符。

标签: java


【解决方案1】:

为什么输出50

您正在从文件中读取第一个字节,字符 2 的 ASCII 值是 50,所以流的第一个字节的值是 50

我应该如何从文件中读取 int

您可以使用扫描仪和方法 nextInt() 从文件中读取数字

工作代码

public class x {
  public static void main(String[] args) {
    try {
      FileWriter fs = new FileWriter("ahmed.txt");
      fs.write("21");

      fs.close();
      FileReader fr = new FileReader("ahmed.txt");
      //String x = Integer.toString(fr.read());
      Scanner s = new Scanner(fr);
      int x = s.nextInt();
      System.out.println(x);
      s.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

一般改进

使用 try-with-resources 可以使代码更干净,也可以修复当前代码存在的漏洞

【讨论】:

    【解决方案2】:

    问题出在你身上,使用了错误的 API

    int x = fr.read();

    见下文。

           fs.close();
            FileReader fr = new FileReader("ahmed.txt");
            //String x = Integer.toString(fr.read());
            //int x = fr.read();
            //System.out.println(x);
    
            BufferedReader br = new BufferedReader(fr);
    
            String sCurrentLine;
    
            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }
            fr.close();
    

    如果您仍想使用您喜欢的代码,请使用:

                int x = fr.read();
                String xs = String.valueOf( (char) x );
                System.out.println(xs);
    
                x = fr.read();
                 xs = String.valueOf( (char) x );
                System.out.println(xs);
    

    需要注意的是String xs = String.valueOf( (char) x ); 将 ascii 值转换为字符串

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多