【每日日报】第三十天---文件操作(字节流)
1 今天继续看了自学手册十二章
字节流写入
1 package File;
2 import java.io.FileOutputStream;
3 import java.io.IOException;
4 import java.io.OutputStream;
5
6 public class FileoutStreamDemo {
7 public static void main(String[] args)throws IOException{
8 out();
9 }
10 public static void out(){
11 OutputStream out=null;
12 try{
13 out=new FileOutputStream("D:/Hello.txt",true);//不带true为重写 ,带true为追加
14 String info="Hello PHP!";
15 byte[] buf=info.getBytes();
16 out.write(buf);
17 }catch(IOException e){
18 e.printStackTrace();
19 }finally{
20 try{
21 if(out!=null) out.close();
22 }catch(IOException e){
23 e.printStackTrace();
24 }
25 }
26 }
27
28 }
字节流读文件
1 package File;
2 import java.io.FileInputStream;
3 import java.io.IOException;
4
5 public class FileInputStreamDemo {
6 public static void main(String[] args)throws IOException{
7 in();
8 }
9 public static void in(){
10 FileInputStream in=null;
11 try{
12 in=new FileInputStream("D:/Hello.txt");
13 byte[] buf=new byte[1024];
14 int len=-1;
15 while((len=in.read(buf))!= -1){
16 String s=new String(buf,0,len);
17 System.out.println(s);
18 }
19 }catch (IOException e){
20 e.printStackTrace();
21 }finally{
22 try{
23 if(in!=null) in.close();
24 }catch(IOException e){
25 e.printStackTrace();
26 }
27 }
28 }
29 }
2 没遇到什么问题
read函数返回读取到的字节数
String(buf,0,len) 将buf从0到len读取到新的字符串中
3 明天继续看书

浙公网安备 33010602011771号