java中对文件的操作

来源:互联网 发布:社交网络百度云盘 编辑:程序博客网 时间:2024/06/03 22:53

A:字节流

一:我们应该建立文件 

,在这其实文件夹和文本文件都是文件,只是文件夹是一个特殊的文件,这句话我们已经建立了一个文件对象,可以对file操作,查找它的路径,字节长度,同时我们注意在操作系统中分配的最小区间是4kb。

对于读文件:我们应该新建一个要读 的对象,为了读取,我们必须建立管道,在读出来的是字节数组,要用String 转化以下。在这里a充当了一个缓存的作用,读入内存时 ,我们应该先将其读入a中,当a满了,或读完了,就可以放入内存。

File file=new File("E:/html/logo.txt");//建对象FileInputStream in=new FileInputStream(file);//建管道int n=0;byte[]  a=new byte[1024];//数据长度一般为1024个长度while((n=in.read(a))!=-1)//将n读入数据a中{String str=new String(a,0,n);//不用这句可能会出乱,因为a是1024System.out.println(str);}对于一些文件的基本操作判断是否存在,若不存在就新建。File file=new File("E:/html5/test.txt");if(!file.exists()){file.createNewFile();}判断是否存在文件夹,若不存在就新建。File file=new File("D:/test");if(!file.isDirectory()){   file.mkdir();}列出文件夹下的所有文件if(file.isDirectory()){File[] file1=file.listFiles();for(int i=0;i<file1.length;i++)System.out.println(file1[i].getName());}二:注意文件中的写 ,关闭我们应该在读取完毕关闭文件,关闭文件时应该注意, 要将其放到finally{}中。写文件与读文件一样,我们应该建立文件,建立通道。File file=new File("E:/html5.txt");FileOutputStream out=null;out=new FileOutputStream(file);String b="asdad";out.write(b.getBytes());三,读取图片文件,并写入另一个图片文件,注意在此 用的是字符流,不能用字节流 。File file=new File("E:/html/logo.jpg");File file1=new File("D:/logo.jpg");try {FileInputStream in=new FileInputStream(file);FileOutputStream out=new FileOutputStream(file1);int n=0;byte[]  a=new byte[1024];try {while((n=in.read(a))!=-1){String str=new String(a,0,n);out.write(a);//System.out.println(str);}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}B:字符流(与上同理)FileReader fr=new FileReader(file);C:缓冲字节流 ,有一个最好的方法,也是提高效率的方法是按行 读取!FileReader file=new FileReader("E:/html/logo.txt");BufferedReader buf=new BufferedReader(file);buf.readLine();他读出的是String,不要再定义一个字节,或字符了!其他不变