本帖最后由 Piaget 于 2015-2-9 09:36 编辑
- package homeWork;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.io.UnsupportedEncodingException;
- public class Work2
- {
- public static void main(String[] args)
- {
- /*
- * 新建一个UFT-8编码的文本文件,用转换流写入一些汉字,然后再读取到控制台上
- */
- File f = new File("aaa.txt");
- //创建输入流
- InputStreamReader isr = null;
- //创建输出流
- OutputStreamWriter osw = null;
- //写入到文件
- try
- {
- osw = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
- osw.write("哈嘻嘻呵呵");
- osw.flush();
- isr = new InputStreamReader(new FileInputStream(f), "utf-8");
- //创建容器
- char [] temp = new char [(int)f.length()] ;
- isr.read(temp);
- // System.out.println(new String(temp));//不加trim()文本文件长度15
- System.out.println(new String(temp).trim());//加trim()文本文件长度还是15
- System.out.println("文件长度"+f.length());
- } catch (UnsupportedEncodingException e)
- {
- e.printStackTrace();
- } catch (FileNotFoundException e)
- {
- e.printStackTrace();
- } catch (IOException e)
- {
- e.printStackTrace();
- }
- finally{
- try
- {
- isr.close();
- osw.close();
- } catch (IOException e)
- {
- e.printStackTrace();
- }
- }
-
- }
- }
复制代码 |
|