How to read a txt file with ObjectInputStream

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jeal4real
    New Member
    • Jul 2010
    • 4

    How to read a txt file with ObjectInputStream

    I am trying to read a txt file with ObjectInputStre am, but it is throwing IOException, the "exc" in the code below shows java.io.StreamC orruptedExcepti on, please I need quick help for this. Thank you in advance.
    Code:
     catch(IOException exc)
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    An ObjectInputStre am loads objects and therefore the corresponding file contains binary data! But a text file contains text and no binary data.
    If you want to read a text file, use FileInputStream ()

    Comment

    • jeal4real
      New Member
      • Jul 2010
      • 4

      #3
      Read a Line with FileInputReader

      So how could I read a line of text with FileInputReader ?

      Comment

      • chaarmann
        Recognized Expert Contributor
        • Nov 2007
        • 785

        #4
        You want to load the text inside the file and store it as a string in memory.
        Try to write your own load methods. By doing so, you'll learn a lot. If you are stuck, list it here what you have done so far, and I will correct it or will give you more hints or will show you the code that solves your problem. It's really not a big task, my code size for reading a file into a string consists of only 7 lines.

        Hwo to do:
        For reading a file, you should make a re-usabel method:
        "public static String readFileAsStrin g(String sourceFileName) throws IOException"
        This method contains source code that uses following classes:
        - class File, methods: File(filename), exists()
        - class FileInputStream , methods: FileInputStream (name), available(), read (byte[] data)
        - class String, methods: new(byte[] data)
        - class IOException, methods: IOException(err orMessage)

        So read about all these classes and the listed methods in the javadocs. That's all you need for assembling the desired method.

        Comment

        Working...