Java 下载空文件并且不应该下载的代码

Java 下载空文件并且不应该下载的代码,java,Java,我有这个功能的一部分,它应该从服务器下载类似pdf的文件并存储在新目录中。它可以做到这一点,但一个空的pdf或文本文件。如何修复它 `File urlfile = new File(host + "/" + path); urlfile.getParentFile().mkdirs(); // create outputstream for request and inputstream for data // downl

我有这个功能的一部分,它应该从服务器下载类似pdf的文件并存储在新目录中。它可以做到这一点,但一个空的pdf或文本文件。如何修复它

 `File urlfile = new File(host + "/" + path);
            urlfile.getParentFile().mkdirs();
            // create outputstream for request and inputstream for data
            // download

            FileOutputStream outS = new FileOutputStream(urlfile);
            DataInputStream instream = new DataInputStream(newsocket.getInputStream());

            // get rid of head part to get to actual file
            String l = null;
            String lastmodtime = null;
            boolean done = false;
            while (!(l = DAA.readLine()).equals("")) {

                if (!done && l.contains("Last-Modified:")) {
                    lastmodtime = l.substring(l.indexOf(' ') + 1, l.length());
                    done = true;
                    System.out.println(l);
                }
            }

            // read in bytes to correct file name
            try {
                byte[] inbytes = new byte[16384];
                int input;
                while ((input = instream.read(inbytes)) != -1) {
                    outS.write(inbytes, 0, input);

                 }
             }`

如果要创建文件的副本,您可以尝试此简单代码,甚至可以使用apache commons io(
FileUtils.copyFile(source,dest)
)进行java复制文件操作

private static void copyFileUsingStream(File source, File dest)
            throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }
    }

这不能编译。好的,bug在哪里?你说得对。它不会进入try-and-the循环,因此不会写入任何内容。你能告诉我我应该做什么吗?你应该准确地描述你遇到的问题,而不是代码应该是什么。基本上,我需要从url下载一个文件并保存在缓存中。但是,我的代码从url下载文件、目录和图片,但pdf或用相同名称保存的文本,但没有写任何内容。