本示例从网上下载一本小说,并保存为 UTF-8 格式。
/**
* 下载文本文件,并以指定的编码保存
* @author hyd
*/
public class DownloadTextAndSave {
// 要下载的文件位置
private static final String FILE_URL = "http://www.9251.com/DownLoad/File/Book/xh/DownloadFile/qzlz20091116.txt";
// 要保存的文件名(或路径)
private static final String SAVE_AS_FILE_NAME = "novel.txt";
// 保存使用的编码
private static final String SAVE_AS_ENCODING = "UTF-8";
// 程序入口
public static void main(String[] args) throws Exception {
String content = download(FILE_URL);
saveAs(content, SAVE_AS_FILE_NAME, SAVE_AS_ENCODING);
}
// 以指定编码保存文件
private static void saveAs(String content, String filename, String SAVE_AS_ENCODING) throws IOException {
// 创建文件
File file=new File(filename);
if (!file.exists()) {
file.createNewFile();
}
// 写入内容
Writer writer = new OutputStreamWriter(new FileOutputStream(file), SAVE_AS_ENCODING);
try {
writer.write(content);
} finally {
writer.close();
System.out.println("文件保存完毕。");
}
}
// 下载指定位置的文本文件,并返回文件内容
private static String download(String FILE_URL) throws MalformedURLException, IOException {
URLConnection conn = new URL(FILE_URL).openConnection();
System.out.println("正在打开 /"" + FILE_URL + "/"...");
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
try {
String line;
StringBuffer result = new StringBuffer();
while ((line = reader.readLine()) != null) {
result.append(line).append("/n");
}
System.out.println("一共读取 " + result.length() + " 个字符。");
return result.toString();
} finally {
reader.close();
}
}
}