importjava.io.File
importjava.io.FileOutputStream
importjava.io.IOException
importjava.io.PrintStream
/**
*@authorzhuruhong
*
*若要变更这个产生的类别注解的范本,请移至
*视窗>喜好设定>Java>程式码产生>程式码和注解
*/
publicclassWriteTxtFileByName{
privateStringfilename=null
publicWriteTxtFileByName(Stringfilename){
this.filename=filename
}
publicvoidwriteFileByName(Stringcontent){
FiledocFile=newFile(filename)
try{
docFile.createNewFile()
FileOutputStreamtxtfile=newFileOutputStream(docFile)
PrintStreamp=newPrintStream(txtfile)
p.println(content)
txtfile.close()
p.close()
}catch(IOExceptione){
e.printStackTrace()
}
}
publicstaticvoidmain(String[]args){
WriteTxtFileByNamewfbn=newWriteTxtFileByName("title")
wfbn.writeFileByName("content")
}
}
给你一个实例。
package filewriter
import java.io.FileWriter
import java.io.IOException
public class IOExceptionDemo {
private static final String LINE_SEPARATOR = System.getProperty("line.separator")
public static void main(String[] args) {
FileWriter fw = null
try {
fw = new FileWriter("k:\\Demo.txt", true)
fw.write("hello" + LINE_SEPARATOR + "world!")
} catch (Exception e) {
System.out.println(e.toString())
} finally {
if (fw != null)
try {
fw.close()
} catch (IOException e) {
throw new RuntimeException("关闭失败!")
}
}
}
}
原因是写入时使用的字符编码和期望的不一致导致的。
java工作区统一编码。统一为utf-8
这个就是输出流的编码问题吧?如果你在输出时指定好具体的编码,或者说指定跟原网页一直的编码。
如果你期望写到文件中的汉字是 GBK编码,可以写文件时,将字符串准换成 GBK编码的byte[]。
网页编码和输出流编码一致。