文件读写,字符流,字节流

1.字符流

//按照指定编码
OutputStreamWriter ops=new OutputStreamWriter(new FileOutputStream("G:\\Java\\tmp\\1.txt",true), 
        "utf-8");

BufferedWriter bw=new BufferedWriter(ops);
bw.write("hello\nworld");
bw.flush();
bw.close();

InputStreamReader isr=new InputStreamReader(new FileInputStream("G:\\Java\\tmp\\1.txt"),
        "utf-8");

//        Scanner scanner=new Scanner(System.in);
BufferedReader br=new BufferedReader(isr);
String str;
while((str=br.readLine())!=null){
    System.out.println(str);
}
br.close();

2.字节流

FileOutputStream fos=null;
FileInputStream fis=null;
try{
    fos=new FileOutputStream("src"+File.separator+"number1.txt",true);
    fis=new FileInputStream("src"+File.separator+"number.txt");
    byte[]b=new byte[4];
    int hasread;
    while((hasread=fis.read(b))>0){
        fos.write(b,0,hasread);
    }
}catch(IOException e){
    e.printStackTrace();
}finally{
    if(fos!=null)
    fos.close();
    if(fis!=null)
    fis.close();
}

 

posted @ 2017-11-09 15:03  fight139  阅读(322)  评论(0编辑  收藏  举报