java 下载txt文件到本地
时间: 2023-11-12 20:05:20 浏览: 42
你可以使用以下代码将txt文件下载到本地:
```java
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {
public static void downloadFile(String fileUrl, String savePath) throws IOException {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection.connect();
InputStream inputStream = new BufferedInputStream(connection.getInputStream());
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
public static void main(String[] args) {
String fileUrl = "https://example.com/file.txt";
String savePath = "C:/path/to/save/file.txt";
try {
downloadFile(fileUrl, savePath);
System.out.println("文件下载成功!");
} catch (IOException e) {
System.out.println("文件下载失败: " + e.getMessage());
}
}
}
```
请注意替换`fileUrl`和`savePath`为你实际的文件URL和保存路径。这段代码将会从指定的URL下载文件,并将其保存到本地。