java tcp服务器未读取文件内容

jyztefdp  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(331)

tcp服务器和tcp客户端的java程序如下。我已将必须读取的文件放在我的java程序所在的同一文件夹中。现在,当我从tcp客户机输入文件名时,tcp服务器将输出抛出为file not found。我错在哪里?非常感谢你的帮助。

tcp服务器

import java.util.Scanner;
import java.net.*;
import java.io.*;
public class TcpServer{
    public static void main(String[] args)throws IOException{
        ServerSocket ss = null;
        Socket s = null;
        try{
            ss = new ServerSocket(3000);
        }
        catch(Exception e){
            e.printStackTrace();
        }
        while(true){
            try{
                System.out.println("Server Ready....");
                s = ss.accept();
                System.out.println("Client Connected...");
                InputStream istream = s.getInputStream();
                Scanner fread = new Scanner(new 
                        InputStreamReader(istream));
                String fileName = fread.nextLine();
                System.out.println("Reading contents of " + fileName);
                Scanner contentRead = new Scanner(new 
                        FileReader(fileName));
                OutputStream ostream = s.getOutputStream();
                PrintWriter pwrite = new PrintWriter(ostream , true);
                while(contentRead.hasNext())
                    pwrite.println(contentRead.nextLine());
                pwrite.close();
                s.close();
            }
            catch(FileNotFoundException e){
                OutputStream ostream = s.getOutputStream();
                PrintWriter pwrite = new PrintWriter(ostream , true);
                System.out.println("File Not Found");
                pwrite.close();
            }
        }
    }
}

tcp客户端

import java.net.*;
import java.io.*;
import java.util.Scanner;
public class TcpClient{
    public static void main( String[] args ){
        Socket s;
        while(true){
            try{
                s = new Socket("127.0.0.1",3000);
                OutputStream ostream = s.getOutputStream();
                System.out.println("Enter filename");
                Scanner input = new Scanner(System.in);
                String fname = input.nextLine();
                PrintWriter pwrite = new PrintWriter(ostream, true);
                pwrite.println(fname);
                InputStream istream = s.getInputStream();
                Scanner cRead = new Scanner(new InputStreamReader(istream));
                while(cRead.hasNext())
                    System.out.println(cRead.nextLine());
                pwrite.close();
                s.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}
dgjrabp2

dgjrabp21#

我猜您在windows系统上运行服务器/客户机应用程序。我认为这是一个路径名相关的问题。因此,可以使用双反斜杠传递文件名,如下示例所示:

C:\\Documents and Settings\\user\\test.txt

相关问题