java读取远程服务器文件

来源:undefined 2025-06-14 15:16:49 0

以下是一个简单的示例代码,用于从远程服务器读取文件内容并将其写入本地文件:

```java

import java.io.*;

import java.net.URL;

public class ReadRemoteFile {

public static void main(String[] args) {

String remoteFileUrl = "http://example.com/remote_file.txt";

String localFilePath = "local_file.txt";

try {

// 创建URL对象

URL url = new URL(remoteFileUrl);

// 打开连接并建立输入流

InputStream inputStream = url.openStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

// 创建本地文件输出流

FileWriter writer = new FileWriter(localFilePath);

// 读取远程文件内容并写入本地文件

String line;

int charCount = 0;

while ((line = reader.readLine()) != null) {

writer.write(line);

charCount += line.length();

// 每写入1000个字符后换行

if (charCount >= 1000) {

writer.write(System.lineSeparator());

charCount = 0;

}

}

// 关闭流

reader.close();

writer.close();

System.out.println("文件下载完成!");

} catch (IOException e) {

e.printStackTrace();

}

}

}

```

在上述代码中,只需将`remoteFileUrl`替换为你要读取的远程文件的URL地址,`localFilePath`替换为你要写入的本地文件路径。代码会从远程服务器读取文件内容,并每写入1000个字符后换行。*,控制台会输出文件下载完成的提示信息。请根据实际情况进行调整。

最新文章