java中对文件的操作

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 block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

B:字符流(与上同理)

FileReader fr=new FileReader(file);

C:缓冲字节流 ,有一个最好的方法,也是提高效率的方法是按行 读取!

FileReader file=new FileReader("E:/html/logo.txt");
BufferedReader buf=new BufferedReader(file);
buf.readLine();
他读出的是String,不要再定义一个字节,或字符了!其他不变


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值