---恢复内容开始---
根据老师布置的作业步骤,下一步进行文件处理。
我在文件读取的时候采用了BufferedReader 类,打算进行逐行读取。此处是对直接从网页上扒下来的源代码(直接存储为*.txt)进行读取,出现乱码问题。
下面展示下代码:
1 package process; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileReader; 6 import java.io.IOException; 7 8 public class readFileByLine { 9 10 public static void main(String[] args) { 11 12 File file = new File("E:/eclipseWorkspace/tixiJG/TTest/003_utf8.txt"); 13 14 readFile(file); 15 16 17 18 } 19 20 public static void readFile(File fileName) { 21 22 String str = ""; 23 BufferedReader buff = null; 24 25 try { 26 27 buff = new BufferedReader(new FileReader(fileName)); 28 int line = 1; 29 while( (str = buff.readLine()) != null) { 30 31 System.out.println("line "+line+": "+str); 32 33 line++; 34 } 35 buff.close(); 36 }catch(IOException e) { 37 38 e.printStackTrace(); 39 } 40 } 41 42 }
修改一、我觉得可能是编码不是默认的utf8,于是将该文件的编码改为utf8,结果依旧乱码。
修改二、经查询API(1.6)我发现InputStreamReader的读取可以指定编码,于是我重新弄了一个程序,经过各种曲折的修改终于正常运行,然而依旧乱码。
修改三、BufferedReader 与 InoutStreamReader 结合起来用,即:
InputStream in = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(in, "utf-8");
BufferedReader buff = new BufferedReader(isr);
完整代码如下:
package process; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /*** * 解决乱码 * @author Administrator * */ public class readFileByLine2 { public static void main(String[] args) { File file = new File("E:/eclipseWorkspace/tixiJG/TTest/003_utf8.txt"); readFile(file); } public static void readFile(File fileName) { try { String str = ""; InputStream in = new FileInputStream(fileName); InputStreamReader isr = null; isr = new InputStreamReader(in, "utf-8"); BufferedReader buff = new BufferedReader(isr); int line = 1; while( (str = buff.readLine()) != null) { System.out.println("line "+line+": "+str); line++; } buff.close(); }catch(IOException e) { e.printStackTrace(); } } }