关键字: 读写文件乱码问题
File f=new File((new BoxConfig()).getBaseDir()+"Data\\"+request.getParameter("ID")+".inc"); BufferedReader reader = new BufferedReader(new FileReader(f)); String line; while((line=reader.readLine())!=null){ strContent+=line; }
File f=new File((new BoxConfig()).getBaseDir()+"Data\\"+request.getParameter("ID")+".inc"); BufferedReader reader = new BufferedReader(new FileReader(f));String line; while((line=reader.readLine())!=null){ strContent+=line; }这是我最初的代码f就是我要读取的UTF-8格式的文本文件,这一天中经过了无数次
的尝试,包括new String(strContent.getBytes("UTF-8"))(其中尝试了N种编码转 换),System.setProperty("file.encoding","UTF-8")(其中指定了N种编码转换 ),都失败了。终于在Google中无数次查询中得到了一个后来被证明很重要的一条 信息“读取文件时指定字符编码”,一语点醒梦中人,.net中不就是这么实现的吗? 走了一圈弯路终于解决了这个问题。File f = new File("E:\\eclipse\\workspace\\box\\Data\\2003-3-7-100.inc"); InputStreamReader read = new InputStreamReader (new FileInputStream(f),"UTF-8"); BufferedReader reader=new BufferedReader(read); String line; while ((line = reader.readLine()) != null) { System.out.println(line); }
File f = new File("E:\\eclipse\\workspace\\box\\Data\\2003-3-7-100.inc"); InputStreamReader read = new InputStreamReader (new FileInputStream(f),"UTF-8"); BufferedReader reader=new BufferedReader(read);String line; while ((line = reader.readLine()) != null) {System.out.println(line); }通过打开文件是指定文件编码的方法把这个问题轻松的解决了。
最后总结一下:java要读取数据流的时候一定要指定数据流的编码方式(至少读取 String流的时候要这么作。2.写文件
File file = new File("c:\a.test"); Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); writer.write("中文测试"); writer.close();