简体   繁体   中英

DataInputStream and DataOutputStream: read and write several times

I've a strange problem with the below example. At the first "iteration" everything works ok, but after the "--------", when I try to write again the same output, I am not able to read anything anymore. I am quite sure that I am missing something. Could you please help me?

Thanks Simone

public class Main {

static final String dataFile = "invoicedata";
static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
static final int[] units = { 12, 8, 13, 29, 50 };
static final String[] descs = { "Java T-shirt", "Java Mug",
        "Duke Juggling Dolls", "Java Pin", "Java Key Chain" };

public static void main(String[] args) throws Exception {
    double price;
    int unit;
    String desc;
    double total = 0.0;

    // OUT
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(new BufferedOutputStream(
            outStream));
    o

    for (int i = 0; i < prices.length; i++) {
        out.writeDouble(prices[i]);
        out.writeInt(units[i]);
        out.writeUTF(descs[i]);
    }

    out.flush();

    // INPUT
    DataInputStream in = new DataInputStream(new BufferedInputStream(
            new ByteArrayInputStream(outStream.toByteArray())));
    System.out.println("AVAL:" +in.available());
    try {
        while (true) {
            price = in.readDouble();
            unit = in.readInt();
            desc = in.readUTF();
            System.out.format("You ordered %d" + " units of %s at $%.2f%n",
                    unit, desc, price);
            total += unit * price;
        }
    } catch (EOFException e) {
    }

    System.out.println("AVAL:" +in.available());

    System.out.println("-------------------------");


    for (int i = 0; i < prices.length; i++) {
        out.writeDouble(prices[i]);
        out.writeInt(units[i]);
        out.writeUTF(descs[i]);
    }

    out.flush();
    System.out.println("AVAL:" +in.available());    


    try {
        while (true) {
            price = in.readDouble();
            unit = in.readInt();
            desc = in.readUTF();
            System.out.format("You ordered %d" + " units of %s at $%.2f%n",
                    unit, desc, price);
            total += unit * price;
        }
    } catch (EOFException e) {
    }
}

}

You're trying to read from an InputStream that has already reached the EOF.

The InputStream is constructed from a byte array containing your 5 products, then you read everything from this InputStream, then you start rewriting products to the OutputStream, but that doesn't modify the byte array at all, which still contains what it contained when it was created initially, and that you have read completely at the first iteration.

Also, you should use objects in your code: instead of having 3 arrays of 5 elements (prices, units and descs), you should have a single array of 5 products, each product being an object having a price, a description and a unit. Java is an OO language. Use objects.

You create the your InputStream at this line:

// INPUT
DataInputStream in = new DataInputStream(new BufferedInputStream(
        new ByteArrayInputStream(outStream.toByteArray())));

Whatever you write into outStream after this point has no effect in what you can read from in afterwards, because you created the DataInputStream with the contents of the byte array at that moment . So you can read what you wrote in the first for loop, but afterwards you are at EOF because the second for loop has no effect in your DataInputStream .

I myself have ran into; if I am correct, this problem; in my case it was when using DataOutputStream with Java Networks.
Your problem could be with the DataOutputStream, when it is not reset it stores the information it first sent, and always sends the same data, so I would add: out.reset();

Secondly you are not sending the Data more than once and your output is not in an infinite loop, so; in turn, it reaches the end of the problem ( EOF ) and stops sending the data over the OutputStream.

Try Adding:

 //OUTPUT
    while(true) {
       //For Loop Which Sends Data
       try {
       Thread.sleep(10);  //The Sleep Is Not Necessary, However It's Recommendable Because 
       }catch(InterruptedException e) {} // of the Lessening of CPU Usage!
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM