关于java.io.FileNotFoundException: test.txt

关于java.io.FileNotFoundException: test.txt ,第1张

今天在使用socket时中io流的文件传输功能时遇到报错:

java.io.FileNotFoundException: test.txt (系统找不到指定的文件。)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.(FileInputStream.java:138)
    at java.io.FileInputStream.(FileInputStream.java:93)
    at Client.main(Client.java:29)

Process finished with exit code 0

经过一番寻找后发现

在文件运行时会产生out文件,而文件的相对路径是根据out文件来定义的,直接写为文件名时要注意将文件与out同级

public class Client
{
    public static void main(String[] args)
    {
        try(Socket socket=new Socket("localhost",8080)) {
            FileInputStream fileInputStream=new FileInputStream("test.txt");
            OutputStream stream=socket.getOutputStream();
            byte[] bytes=new byte[1024];
            int i;
            while ((i=fileInputStream.read(bytes))!=-1)
            {
                stream.write(bytes,0,i);
            }
            fileInputStream.close();
            stream.flush();

        }catch (IOException e)
        {
            e.printStackTrace();
        }

    }

}
public class Server
{
    public static void main(String[] args)
    {
        try(ServerSocket sever=new ServerSocket(8080))
        {
            Socket socket=sever.accept();
            InputStream stream=socket.getInputStream();
            FileOutputStream fileOutputStream=new FileOutputStream("net\aa.txt");
            byte[] bytes=new byte[1024];
            int i;
            while ((i=stream.read(bytes))!=-1)
            {
                fileOutputStream.write(bytes,0,i);
            }
            fileOutputStream.flush();
            fileOutputStream.close();

        }catch (IOException e)
        {
            e.printStackTrace();
        }

    }
}

 同级关系  切记!!!!!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/796672.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-06
下一篇2022-05-06

发表评论

登录后才能评论

评论列表(0条)

    保存