如何使用Java下载文件并将其移动到目录?

3

我寻找一些使用Java下载文件并将其移动到不同目录的脚本或教程,但是我看到很多类似于我的问题都得到了回答,但它们都有所不同。是否有明确的方法来实现这个?我目前正在学习Java,并没有足够的经验来制作这样的脚本。有谁可以帮忙吗?


“下载和移动”是指从互联网下载文件到指定文件夹吗? - Stefano Sanfilippo
是的,抱歉,我没有指定。 - user2422742
1个回答

3

我认为这是从网络上下载文件的最佳方法。当你下载文件时,它会被存储在当前正在运行的程序中,除非你特别指定将其存储在硬盘上。

            URL url;
            URLConnection con;
            DataInputStream dis; 
            FileOutputStream fos; 
            byte[] fileData;  
            try {
                url = new URL("http://website.com/file.pdf"); //File Location goes here
                con = url.openConnection(); // open the url connection.
                dis = new DataInputStream(con.getInputStream());
                fileData = new byte[con.getContentLength()]; 
                for (int q = 0; q < fileData.length; q++) { 
                    fileData[q] = dis.readByte();
                }
                dis.close(); // close the data input stream
                fos = new FileOutputStream(new File("/Users/kfang/Documents/Download/file.pdf")); //FILE Save Location goes here
                fos.write(fileData);  // write out the file we want to save.
                fos.close(); // close the output stream writer
            }
            catch(Exception m) {
                System.out.println(m);
            }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接