Java 通过URL地址下载文本内容到本地文件中

HTTP传输协议过程中,HTTP服务器在每个响应前面的首部中提供了大量信息,例如,下面一个Apache Web服务器返回的一个典型的HTTP首部:这里写图片描述
通过URL进行资源下载时,创立连接,使用getContentType()确定文本类别,比如只下载txt文件,我们将指定非Content-Type里面非text文件,抛出异常。然后通过getContentLength()获取文本大小,通过IO流将文本内容保存到本地指定文件内。
代码如下:

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class BinarySaver {

    private final static String url = "地址";

    public static void main(String[] args) {
        try {
            URL root = new URL(url);
            saveBinary(root);
        } catch (MalformedURLException e) {
            // TODO: handle exception
            System.out.println(url + "is not URL");
        } catch (IOException e) {
            // TODO: handle exception
            System.out.println(e);
        }
    }

    public static void saveBinary(URL u) throws IOException {
        // TODO Auto-generated method stub
        URLConnection uc = u.openConnection();
        String contentType = uc.getContentType();
        int contentLength = uc.getContentLength();
        /*
         * 可以限制不下载哪种文本文件
        if (contentType.startsWith("text/") || contentLength == -1) {
            throw new IOException("This is not a binary file.");
        }*/

        try (InputStream raw = uc.getInputStream()) {
            InputStream in = new BufferedInputStream(raw);
            byte[] data = new byte[contentLength];
            int offset = 0;
            while (offset < contentLength) {
                int bytesRead = in.read(data, offset, data.length - offset);
                if (bytesRead == -1) {
                    break;
                }
                offset += bytesRead;
            }

            if (offset != contentLength) {
                throw new IOException("Only read " + offset
                        + " bytes; Expected " + contentLength + " bytes");
            }
            String filename = "存储位置";
            try (FileOutputStream fout = new FileOutputStream(filename)) {
                fout.write(data);
                fout.flush();
            }
        }
    }


}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要通过Java从网络地址下载文件,可以使用Java标准库java.net包URLConnection和InputStream。 以下是一个简单的示例,演示如何从URL下载文件并将其保存到本地文件系统: ```java import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class FileDownloader { public static void main(String[] args) throws Exception { String fileUrl = "https://example.com/file-to-download.txt"; String localFilePath = "/path/to/local/file.txt"; URL url = new URL(fileUrl); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); FileOutputStream outputStream = new FileOutputStream(localFilePath); byte[] buffer = new byte[1024]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); System.out.println("File downloaded to " + localFilePath); } } ``` 在上面的代码,我们首先定义要下载文件URL和本地文件系统的路径。然后,我们使用URL对象创建一个URLConnection对象,并使用该对象的getInputStream()方法获取到文件的输入流。 我们还创建了一个FileOutputStream对象,该对象用于将文件写入本地文件系统。我们使用一个缓冲区读取输入流,并使用FileOutputStream将读取的字节写入本地文件系统。最后,我们关闭文件输出流和输入流,并打印一条消息,指示文件已成功下载到本地文件系统。 请注意,上面的示例假定下载文件文本文件。如果您要下载文件是二进制文件(例如图像或视频文件),则需要使用更适合二进制数据的缓冲区大小。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值