1、JAVA读取文件,避免中文乱码。
/** * 读取文件内容 * * @param filePathAndName * String 如 c:\\1.txt 绝对路径 * @return boolean */ public static String readFile(String filePathAndName) { String fileContent = ""; try { File f = new File(filePathAndName); if(f.isFile()&&f.exists()){ InputStreamReader read = new InputStreamReader(new FileInputStream(f),"UTF-8"); BufferedReader reader=new BufferedReader(read); String line; while ((line = reader.readLine()) != null) { fileContent += line+"\n"; } read.close(); } } catch (Exception e) { System.out.println("读取文件内容操作出错"); e.printStackTrace(); } return fileContent; }
2、JAVA写入文件,避免中文乱码。
public static void writeFile(String filePathAndName, String fileContent) { try { File f = new File(filePathAndName); if (!f.exists()) { f.createNewFile(); } OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"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(fileContent); writer.close(); } catch (Exception e) { System.out.println("写文件内容操作出错"); e.printStackTrace(); } }
若写入的时候用
1、PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName)));
2、PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName));
都会出现错误,不行。
p.s. 我刚开始用上述方法的时候还是出先乱码,后来发现是因为我的html文件的编码方式是不是utf-8,改成utf-8即可。
查看一个文件的编码方式,一个简单的办法是:用记事本打开它,然后另存为一个副本文件,在“另存为”的页面下方,“保存”按钮前面,如下图所示,会出现原文件的编码方式。
如果不是UTF-8,把它改成UTF-8,保存即可。
更多java知识请关注java基础教程栏目。
위 내용은 Java에서 HTML 파일을 읽고 쓸 때 잘못된 코드에 대한 솔루션의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!