Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

I/O streams confusion

Status
Not open for further replies.

VicM

Programmer
Sep 24, 2001
444
US
In an attempt to understand the various I/O streams that Java supports, and their relationships to each other, I came across this bit of code, which on the surface, looks like it should work.

However, on the output side, when firtst reading from BufferedReader input and then from DataInputStream input, the program throws an IO exception. he exception is not thrown when changing the read from DataInputStream to BufferedReader; only the other way around.

Does anyone have any suggestions as to why this is so? Is it a software bug or does the program not use the streams properly?

Code:
import java.io.*;
public class IOProblem {

public static void main(String[] args) throws IOException
{
	DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("Data.txt")));
	out.writeDouble(3.14159);
	out.writeBytes("That was the value of pi\n");
	out.writeBytes("This is pi/2:\n");
	out.writeDouble(3.14159/2);
	out.close();
	
	DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("Data.txt")));
	BufferedReader inbr = new BufferedReader(new InputStreamReader(in));
	System.out.println(in.readDouble());
	System.out.println(inbr.readLine());
	System.out.println(inbr.readLine());
	System.out.println(in.readDouble());
}
}

Thanks,
Vic
 
Well - the nested Streams and Readers are a bit confusing and I refused to keep them in mind.
I look into existing code and take what worked before.

Mostly you know two facts: The source of the data, and the way you want to handle it.
Source may be a file, or System.in.
Handling: use a readLine () function.

Then you have to find a path from the first to the second. :)

The normal way is Stream<-Stream<-Stream<-... or Reader<-Reader<-Reader<-... .
Sometimes you need to switch from Stream to Reader.
Therefore you use the bridge: InputStreamReader.
...<-Reader<-Reader<-InputStreamReader<-Stream<-Stream<-...

Well - and Buffering is only useful once.
So your code might be like this:
Code:
InputStreamReader isr = new InputStreamReader (new FileInputStream("Data.txt"));
BufferedReader inbr = new BufferedReader ((isr));

But perhaps the problem is mainly coming from reading the same stream in two ways - as DIS and BR. I guess the behaviour of such actions is pretty undefined.

I guess the DIS is overconfused when written the second time directly with 'readDouble'.
He thought we would use him only as BufferedReader. Perhaps the Buffer is already filled (therefore: Buffered) with things, read from the DIS. DIS might now be empty - perhaps reading would succeed, if there was some more data (10kb ?).

dont't visit my homepage:
 
Well you can combine different kind of readers and writes to do different things. Heres a runnable example of the different things you might want to do.

Code:
package tektips;

import java.io.*;
import java.util.List;
import java.util.ArrayList;

public class Readers {
    public static void main(String[] args) {


        File file = new File("Sample.txt");
        Readers sample = new Readers();

        //Writes/Reads text
        sample.writeTextFile(file);
        sample.readTextFile(file);

        //Writes/Reads byte streams
        file = new File("bytes.dat");
        sample.writeBytesToFile(file);
        sample.readBytesFromFile(file);

        //Writes/Reads primitive data types
        file = new File("primitives.dat");
        sample.writeDataToFile(file);
        sample.readDataFromFile(file);

        //Writes/Reads objects
        file = new File("list.obj");
        sample.writeObjectToFile(file);
        sample.readObjectFromFile(file);

    }

    /**
     * Writes text into a file
     * @param file A File object reference
     * */
    public void writeTextFile(File file){
        try{

            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            out.write("Hello world!");
            out.close();

        }catch(IOException e){
            e.printStackTrace();
        }
    }


    /**
     * Reads text from a file
     * @param file A File object reference
     * */
    public void readTextFile(File file){
        if (file.exists()){
            try{

                BufferedReader in = new BufferedReader(new FileReader(file));
                String line;
                while ( (line = in.readLine() ) != null){
                    System.out.println(line);
                }
                in.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }


    /**
     * Writes bunches of bytes into a file
     * @param file A File object reference
     * */
    public void writeBytesToFile(File file){
        try{
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));

            byte[] myBytes = new byte[] {0,1,2,3,4,5,6,7,8,9};

            out.write(myBytes);
            out.close();

        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    /**
     * Reads bunches of bytes from a file
     * @param file A File object reference
     * */
    public void readBytesFromFile(File file){
        if (file.exists()){
            try{
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));

                byte[] myBytes = new byte[10];

                in.read(myBytes);
                in.close();

                for(int i=0;i<10;i++){
                    System.out.println(myBytes[i]);
                }
            }catch(FileNotFoundException e){
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }

    /**
     * Writes primitive data types
     * @param file A File object reference
     * */
    public void writeDataToFile(File file){
        try{
            DataOutputStream out = new DataOutputStream(new FileOutputStream(file));

            out.writeBoolean(false);
            out.writeByte(10);
            out.writeChar('D');
            out.writeDouble(25.34D);
            out.writeInt(40000);
            out.writeLong(24567L);
            out.writeUTF("Hello world");

        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    /**
     * Reads primitive data types from a file
     * @param file A File object reference
     * */
    public void readDataFromFile(File file){
        try{

            DataInputStream in = new DataInputStream(new FileInputStream(file));

            System.out.println(in.readBoolean());
            System.out.println(in.readByte());
            System.out.println(in.readChar());
            System.out.println(in.readDouble());
            System.out.println(in.readInt());
            System.out.println(in.readLong());
            System.out.println(in.readUTF());

            in.close();

        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    /**
     * Writes objects into a file
     * @param file A File object reference
     * */
    public void writeObjectToFile(File file){

        //Objecto to serialize
        List myList = new ArrayList();

        myList.add("Lord");
        myList.add("of");
        myList.add("Code");

        try{
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
            out.writeObject(myList);
            out.close();
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    /**
     * Reads an objects from a file
     * @param file A File object reference
     * */
    public void readObjectFromFile(File file){
        List myList;
        if (file.exists()){
            try{
                ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));

                myList = (List) in.readObject();
                in.close();

                int size = myList.size();
                for (int i = 0;i<size;i++){
                    System.out.println(myList.get(i));
                }

            }catch(ClassNotFoundException e){
                e.printStackTrace();
            }catch(FileNotFoundException e){
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }

}

I hope it helps.


edalorzo@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top