使用java BufferedReader从网络中读取文件到本地,可以存入数据库,也可以保存到本地
java代码
1.下载网络文件内容转换成StringBuffer
/** 从网络地址url下载文件读成字符串
* @param downloadUrl 文件的网络地址
* @return
*/
public static StringBuffer downloadFromUrl(String downloadUrl) {
BufferedReader reader = null;
StringBuffer stringBuffer = new StringBuffer();
String line;
try {
URL url = new URL(downloadUrl);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
return stringBuffer;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
2.将字符串保存成指定路径的文件
public static void saveAsFile(String content,String fileName) throws FileNotFoundException {
File file=new File(fileName);
PrintStream ps =new PrintStream(new FileOutputStream(file));
ps.append(content);
ps.flush();
}
时间: 2024-11-02 11:50:37