File 将UDP套接字数据保存到文件中
我有一个代码来发送和接收UDP套接字 发送UDP代码:File 将UDP套接字数据保存到文件中,file,sockets,datagram,File,Sockets,Datagram,我有一个代码来发送和接收UDP套接字 发送UDP代码: public static void main(String args[]) throws Exception { try { FileOutputStream fo = new FileOutputStream("OUTFILE.txt"); PrintStream ps = new PrintStream(fo); DatagramSocket Soc
public static void main(String args[]) throws Exception
{
try
{
FileOutputStream fo = new FileOutputStream("OUTFILE.txt");
PrintStream ps = new PrintStream(fo);
DatagramSocket Socket = new DatagramSocket(4555);
byte[] receiveData = new byte[1000000];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
while(true)
{
receivePacket.setLength(receiveData.length);
Socket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.printf("RECEIVED: %s " , new String(receivePacket.getData()));
ps.println(sentence);
ps.println();
ps.close();
fo.close();
}
File file = new File("OUTFILE.txt");
FileInputStream fis = new FileInputStream(file);
byte[] fsize = new byte[(int) file.length()];
int size = fis.read(fsize);
System.out.println("Received Size = " + size);
}
catch (Exception e) {
System.err.println(e);
}
}
}
我想将每个接收到的数据包的值写入文件,然后得到整个文件的大小。
在我的代码中,我刚刚得到写入文件的第一个接收值。
您能告诉我如何在文件中写入整个接收值。在第一个循环结束时,您正在关闭流,因此无法写入其他行。您需要移动
ps.close()
和fs.close()。此外,您还有一个不确定的循环,它保证从文件读取的代码不能被调用——您需要有某种机制来确定何时停止循环。谢谢您,但是将.close()移到循环之外是不起作用的。如果(receivePacket.getLength()==0),我尝试了这个条件来停止循环打破但它并没有停止循环,这不是打破循环的有效方法。阅读JavaDoc:“这个方法会一直阻塞直到收到数据报。数据报数据包对象的长度字段包含接收到的消息的长度。”Nate能告诉我如何停止循环吗??