将数据从 datainputstream 写入 Java 中的文件
Write data from datainputstream to a file in Java
我正在从下面的 link 学习 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 的文件,并将数据输入流的内容复制到该文件中。但只有当我键入 Over 时,Over 一词才会被复制到文件中,而不会复制任何其他内容。我在这里做错了什么?
What am I doing wrong here?
每次阅读一行时,您都在重新创建一个新文件。
创建一个文件,在开头一次,然后将您的行写入其中。
我正在从下面的 link 学习 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 的文件,并将数据输入流的内容复制到该文件中。但只有当我键入 Over 时,Over 一词才会被复制到文件中,而不会复制任何其他内容。我在这里做错了什么?
What am I doing wrong here?
每次阅读一行时,您都在重新创建一个新文件。
创建一个文件,在开头一次,然后将您的行写入其中。