读取文件:
File f = new File("e:/记事本.txt"); FileInputStream fis = new FileInputStream(f);
如果是fis.read():读取一个字节(英文)
中文是两个字节:一次读取两个字节不会出现乱码
int i = 0; byte[] b=new byte[2]; white((i=fis.read(b))!=-1){ System.out.println(new String(b)); }
中英文混合输出记事本中内容。则读取的长度应该为整个文本的长度才不会出现乱码。
byte[] b=new byte[(int) f.length()]; int m = 0; while((m=fis.read(b))!=-1){ System.out.print(new String(b)); }
写文件:
static void testWrite(){ FileOutputStream fos=null; String str="hahhsbf"; try { fos = new FileOutputStream("e:/记事本.txt"); for (int i = 0; i < str.length(); i++) { fos.write(str.charAt(i)); } fos.write('z'); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { if(fos!=null){ fos.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
但是这种写入 是覆盖文件中原来的内容!