[英]Write data from datainputstream to a file in Java
我正在從以下鏈接學習 Java 中的套接字編程: https : //www.geeksforgeeks.org/socket-programming-in-java/
教程中的服務器代碼如下(我添加了額外的行以復制到文件中):
// A Java program for a Server
import java.net.*;
import java.io.*;
public class Server
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
FileWriter fw;
// constructor with port
public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
fw = new FileWriter("out.txt");
fw.write(line);
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
fw.close();
// close connection
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server server = new Server(5000);
}
}
我在此代碼中為 filewriter 添加了額外的行,我在其中創建了一個名為out.txt的文件並將 datainputstream 的內容復制到文件中。 但只有當我輸入Over 時,單詞Over才會被復制到文件中,而不是任何其他內容。 我在這里做錯了什么?
我在這里做錯了什么?
每次閱讀一行時,您都會再次創建一個新文件。
在開始時創建一個文件,然后將您的行寫入其中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.