【问题标题】:Reading multiple lines from a byte stream从字节流中读取多行
【发布时间】:2013-11-18 10:24:05
【问题描述】:

我注意到,每当您使用 FileOutputStream 并将 append 设置为 true 时,附加的对象都会放在不同的行上。

我的问题是如何使用ObjectInputStream 读取多行数据。

例如:

public class StringBytes {

    public static void main(String[] args) throws Exception {
        String S1 = "Hi";
        String S2 = "\n"+"Bye";
        String file = "C:\\HiBye.out";


        FileOutputStream fileOutputStream = new FileOutputStream(file);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(S1);

        fileOutputStream = new FileOutputStream(file,true);
        objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(S2);



        FileInputStream fileInputStream = new FileInputStream(file);
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

        String SS = (String) objectInputStream.readObject();
        System.out.println(SS);

    }
}

上面的输出是Hi,因为Bye 在不同的行上,它不会被读取。 我还是一个初学者,所以所有的帮助表示赞赏

【问题讨论】:

    标签: java fileinputstream objectinputstream


    【解决方案1】:

    您在文件中写入了两个对象(String 的实例):s1 和 s2。 你只读取了一个对象,第一个。

    如果您希望将其视为单个字符串,则需要 s1 为 "Hey" + \n + "Bye"。 或者,你可以调用readObject()两次,得到第二个对象

    【讨论】:

    • 如果你不知道有多少行怎么办?您将如何遍历文件?
    • 你可以用 try 和 catch EOFException 包围它,然后迭代直到它失败。还有其他艰难的方法。这里有一些很好的答案:stackoverflow.com/questions/2626163/…
    【解决方案2】:

    使用ObjectOutputStreamObjectInputStream,所有内容都以二进制格式存储在文件中,因此查看文件不会提供太多信息。

    您放入文件中的内容以及之后从输入流中获得的内容都是单独的对象。要同时获得Strings,您需要调用readObject() 两次,为您最初拥有的每个writeObject() 调用一次。

    如果您想使用文本文件,可以查看BufferedReaderBufferedWriter。如果您有兴趣一次阅读整个文本文件,请查看What is simplest way to read a file into String?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-26
      • 2021-04-03
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      • 2015-12-01
      • 1970-01-01
      相关资源
      最近更新 更多