首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FileInputStream错误

FileInputStream错误
EN

Stack Overflow用户
提问于 2013-06-03 19:42:48
回答 9查看 335关注 0票数 0

我有这段代码,只是想把它写到一个文件中。但是当我编译它的时候,它没有显示任何错误,但是我的文件中的文本是不可读的,一些Unicode代码等等。我使用eclipse IDE。这可能是什么原因呢?

代码语言:javascript
复制
public static void main(String[] args) {

    String s = "Hello world!";
    int i = 143141141;
    try
    {
        //create new file with an ObjectOutputStream
        FileOutputStream out = new FileOutputStream("test.txt");
        ObjectOutputStream oout = new ObjectOutputStream(out);

        //write something in a file
        oout.writeObject(s);
        oout.writeObject(i);
        //close the stream
        oout.close();

        //create an ObjectInputStream for the file we created before
        ObjectInputStream ois = new ObjectInputStream(
                                                new FileInputStream("test.txt"));
        //read and print what we wrote before
        System.out.println("" + (String) ois.readObject());
        System.out.println("" + ois.readObject());
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
}
EN

回答 9

Stack Overflow用户

发布于 2013-06-03 19:48:21

使用ObjectOutputStream,您可以使用Serialization将对象写入文件。序列化使用编码系统,您可以在程序中正确使用ObjectInputStream来解码这些对象。但是您将无法读取序列化过程创建的文件中的信息。

票数 2
EN

Stack Overflow用户

发布于 2013-06-03 19:49:06

由于您使用的是ObjectOutputStream和ObjectInputStream,它将以不可读的目标代码编写,而且当您从文件中读取时,它将以对象的形式出现,

使用BufferedReader或Writer将字符串写入文件,可读

代码语言:javascript
复制
FileReader f=new FileReader(new File("test.txt"));
BufferedReader f1=new BufferedReader(f)

票数 2
EN

Stack Overflow用户

发布于 2013-06-03 19:47:06

你应该用PrintWriter写文本文件,ObjectOutputStream写二进制数据。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16895910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档