【问题标题】:I cannot store data in a file; instead it stores in binary form [duplicate]我无法将数据存储在文件中;相反,它以二进制形式存储[重复]
【发布时间】:2016-04-12 06:52:05
【问题描述】:

我想将数据存储在创建的文件中,但我的代码将二进制语言存储在文件中。谁能帮我存储一个字符串?

import java.io.*;
import java.util.*;
class WriteToFileExample {
    public static void main(String args[]) {
        try {
            // Create file 
            FileWriter fstream = new FileWriter("out.txt");
            BufferedWriter out = new BufferedWriter(fstream);
            Scanner sc = new Scanner(System.in);
            System.out.println("enter name");
            int a = sc.nextInt();
            out.write(a);
            out.close();
        } catch (Exception e) {


            //Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
}

【问题讨论】:

  • 将其写为字符串 (write(a + "", 0, 1))。但可能有更清洁的解决方案
  • Read the Javadoc 表示您正在调用的 write 方法。
  • 你想要一个名字,它传统上是一个字符串,因为我们不会用数字给人们命名(我认为),然后使用@987654324 读取它@。迷人!

标签: java


【解决方案1】:

您正在使用 Scanner.nextInt() 输入字符串。变化:

int a = sc.nextInt()

到

String a = sc.next()

更广泛的问题是,当您在 BufferedWriter 中使用“write(int)”方法时,您正在写入整数指定的字符。这意味着您正在编写由您输入的整数表示的任何 ASCII 字符——例如,如果您在代码中输入“65”,您将得到一个带有大写字母 A 的文本文件,因为A 是 ASCII #065。

这是字符的 ASCII 值表:http://web.cs.mun.ca/~michael/c/ascii-table.html

如您所见,前 20 个左右并不是您想象中的字母或数字。如果您愿意,您可以尝试将其中一些字符的整数值输入到您的代码中,以查看它是如何工作的。

【讨论】:

  • 阅读本身不是问题。阅读int 并没有错,问题在于int 的编写方式。
  • 你是对的,但如果有人仍在使用 Scanner 类来处理这类事情,那么我不确定 Javadoc 对“指定要写入的字符的 int”的描述有多大帮助。我编辑了答案以详细说明
猜你喜欢
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多