[英]How to read a datainputstream when using a dataoutputstream to write bytes to socket?
[英]DataInputStream and DataOutputStream: read and write several times
我在以下示例中遇到了一個奇怪的問題。 在第一個“迭代”中,一切正常,但是在“ --------”之后,當我嘗試再次寫入相同的輸出時,我不再能讀取任何內容。 我很確定我缺少一些東西。 請你幫助我好嗎?
謝謝西蒙妮
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) {
}
}
}
您正在嘗試從已經到達EOF的InputStream中讀取。
InputStream由包含5個產品的字節數組構造而成,然后從此InputStream中讀取所有內容,然后開始將產品重寫為OutputStream,但這根本不修改字節數組,該字節數組仍包含它包含的內容。最初是創建的,並且在第一次迭代時已完全閱讀。
另外,您應該在代碼中使用對象:您應該具有5個產品的單個數組,而不是由5個元素(價格,單位和descs)組成的3個數組,每個產品都是具有價格,描述和單位的對象。 Java是一種OO語言。 使用對象。
您可以在此行創建InputStream:
// INPUT
DataInputStream in = new DataInputStream(new BufferedInputStream(
new ByteArrayInputStream(outStream.toByteArray())));
不管你寫入outStream
這一點在你可以讀什么沒有效果后in
算賬,因為你創造了DataInputStream
用的那一刻字節數組的內容。 因此,您可以閱讀在第一個for
循環中編寫的內容,但之后您將處於EOF,因為第二個for
循環在DataInputStream
無效。
我自己遇到了; 如果我是正確的,這個問題; 就我而言,是在Java Networks中使用DataOutputStream
時。
您的問題可能出在DataOutputStream上,當不重置時,它將存儲它首先發送的信息,並且始終發送相同的數據,因此我要添加: out.reset();
其次,您發送數據的次數不會超過一次,並且您的輸出不會處於無限循環中。 反過來,它到達問題的盡頭( EOF
),並停止通過OutputStream發送數據。
嘗試添加:
//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!
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.