gpt4 book ai didi

java - 无法将整数文件写入java中的文件

转载 作者:行者123 更新时间:2023-12-02 00:22:55 24 4
gpt4 key购买 nike

我正在尝试将计算的数据速率的输出保存在文件中。数据速率是整数类型,我无法将其保存在文件中,并且出现以下错误:

Exception in thread "main" java.io.IOException: Write error
at java.io.FileOutputStream.write(Native Method)
at java.io.DataOutputStream.write(Unknown Source)
at UDPSend.main(UDPSend.java:60)

代码如下:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class UDPSend {


public static void main(String[] args) throws IOException
{
FileInputStream fstream = new FileInputStream("T.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String path="DataRateBefore.txt";
FileOutputStream f = new FileOutputStream(path);
DataOutputStream fo = new DataOutputStream (f);
InetAddress addr = InetAddress.getByName("localhost");
byte[] buf = new byte[10000];

String DataLine;
long lastTime = System.currentTimeMillis();
long firstTime = lastTime;
int nobits = 0;

long start = System.currentTimeMillis();
System.out.println("Start Time: " + start);

while ((DataLine = br.readLine()) != null)
{
DatagramPacket packet =new DatagramPacket(DataLine.getBytes(),DataLine.length() , addr, 4553);
System.out.println (DataLine);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);

nobits+=packet.getLength() * 8;
System.out.println(packet.getLength());
System.out.println("no of bits is:");
System.out.println(nobits);



if ((System.currentTimeMillis() - lastTime) > 11)
{
lastTime = System.currentTimeMillis();
System.out.println("data rate is ");
System.out.println(nobits);
fo.write(nobits);
nobits= 0;
fo.close();
fo.flush();
}

}//end while loop

// Get the end time of the process
long end = System.currentTimeMillis();
System.out.println("End Time : " + end);
long elapsedTime = end - start;
// Show how long it took to finish the process
System.out.println("The process took approximately: " + elapsedTime + " milliseconds");
}//end main method
}

谁能帮我解决这个问题吗?

最佳答案

关闭流后,您不应再尝试对其进行任何操作。考虑:

fo.close(); 
fo.flush();

您至少需要交换这两行。另外,要么重新打开 fo,以便您可以在循环的其他迭代中写入它,要么不要在循环中间关闭它(但在循环完成之后)。

关于java - 无法将整数文件写入java中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10603109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com