即使我检查文件是否存在,FileOutputStream也会创建文件

时间:2016-04-24 17:44:37

标签: java sockets

我正在制作简单的客户端 - 服务器应用程序,以便在服务器上制作文件副本。

有用于向服务器发送文件的客户端方法:

private void makeCopy(Socket clientSock) throws IOException {
        File file = new File("D:\\client\\toCopy.bmp");
        File dest = new File("D:\\server\\copyFile.bmp");
        boolean ifExists = dest.exists();
        if(ifExists && !file.isDirectory()){
            System.out.println("Copy is already made on server.");
        }
        else{
            fis = new FileInputStream(file);
            byte[] buffer = new byte[4096];
            while (fis.read(buffer) > 0) {
                oos.write(buffer);
            }
            //fis.close();
            oos.close();
        }

    }

还有用于从客户端接收文件的服务器端方法:

public void saveFile(Socket s) throws IOException{

        File copy = new File("D:\\server\\fileCopy.bmp");
        fos = new FileOutputStream(copy);
        File fromServer = new File("D:\\client\\toCopy.bmp");
        if(copy.exists() && !copy.isDirectory()){

        }
        else{
            byte[] buffer = new byte[4096];

            int filesize = (int)fromServer.length();
            int read = 0;
            int totalRead = 0;
            int remaining = filesize;
            while((read = ois.read(buffer, 0, Math.min(buffer.length, remaining))) > 0) {
                totalRead += read;
                remaining -= read;
                System.out.println("read " + totalRead + " bytes.");
                fos.write(buffer, 0, read);
            }
        }
    }

问题是,即使我检查文件存在,它仍然会生成我无法打开的文件(写入0字节)。有什么想法吗?

1 个答案:

答案 0 :(得分:-1)

FileOutputStream在文件系统中创建文件输出流和文件。 首先,您应检查存在,然后创建FileOutputStream。

File copy = new File("D:\\server\\fileCopy.bmp");
if(copy.exists() && !copy.isDirectory()){ }
fos = new FileOutputStream(copy);
File fromServer = new File("D:\\client\\toCopy.bmp");