直接使用FileWriter无法指定编码方式,OutputStream可以指定
public class transCode {
// 把JSOUP读取的网页转换成HTML格式的文件保存下来进行分析,写文件时候需要指定编码的格式
public static void main(String args[]) throws IOException{
String seed = "http://channel.jd.com/electronic.html";
String docstr = getWebDocstr(seed);
saveFile(docstr);
}
public static String getWebDocstr(String url) throws IOException{//用JSOUP得到文档对象模型的字符形式
Document doc = Jsoup.connect(url).get();
String docstr = doc.toString();
return docstr;
}
public static void saveFile(String str){//把读取的document对象转变成为字符串进行读取并写入到HTML文件中,指定写
//输出写的编码格式为UFT-8
String filepath = "d:/bbc.html";
File file = new File(filepath);
try {
if (!file.exists()) {
file.createNewFile();
}
//OutputStreamWriter 是字符流通向字节流的桥梁:可使用指定的 charset 将要写入流中的字符编码成字节
//它使用的字符集可以由名称指定或显式给定,否则将接受平台默认的字符集。
//为了获得最高效率,可考虑将 OutputStreamWriter 包装到 BufferedWriter 中,以避免频繁调用转换器
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
BufferedWriter writer=new BufferedWriter(write);
//PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName)));
//PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName));
writer.write(str);
writer.close();
} catch (Exception e) {
System.out.println("写文件内容操作出错");
e.printStackTrace();
}
}
}
public class transCode {
// 把JSOUP读取的网页转换成HTML格式的文件保存下来进行分析,写文件时候需要指定编码的格式
public static void main(String args[]) throws IOException{
String seed = "http://channel.jd.com/electronic.html";
String docstr = getWebDocstr(seed);
saveFile(docstr);
}
public static String getWebDocstr(String url) throws IOException{//用JSOUP得到文档对象模型的字符形式
Document doc = Jsoup.connect(url).get();
String docstr = doc.toString();
return docstr;
}
public static void saveFile(String str){//把读取的document对象转变成为字符串进行读取并写入到HTML文件中,指定写
//输出写的编码格式为UFT-8
String filepath = "d:/bbc.html";
File file = new File(filepath);
try {
if (!file.exists()) {
file.createNewFile();
}
//OutputStreamWriter 是字符流通向字节流的桥梁:可使用指定的 charset 将要写入流中的字符编码成字节
//它使用的字符集可以由名称指定或显式给定,否则将接受平台默认的字符集。
//为了获得最高效率,可考虑将 OutputStreamWriter 包装到 BufferedWriter 中,以避免频繁调用转换器
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
BufferedWriter writer=new BufferedWriter(write);
//PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName)));
//PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName));
writer.write(str);
writer.close();
} catch (Exception e) {
System.out.println("写文件内容操作出错");
e.printStackTrace();
}
}
}