java文件读写

 一、java读文件的多种方式:

    1、以字节的方式,每次读取一个字节

		try {
                         //str1为文件路径
			FileInputStream fip=new FileInputStream(str1);  
                         int n=0
			while((n=fip.read())!=-1){  //fip.read()方法,读取的时候是一个字节一个字节读取的
                              System.out.println(n);
			}
			fip.close();    //输入流如水龙头一样,不用时要将其关闭,不然会一直在读取状态
		} catch (FileNotFoundException e) {
			// TODO: handle exception
			System.out.println("没有找到文件!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    2、以行为单位,一次读一行。如上所说read()方法每次制度一个字节,读取的文件小一点还能忍,文件一大,运行起来特别慢,耗费时间。因此还是偏向于用一行行读的读取方式。

try {
			FileInputStream fip =new FileInputStream(str1);   //str1为读取的文件路径
			BufferedReader bfr=new BufferedReader(new InputStreamReader(fip));  //如果单纯的使用fip.read()一个字节一个字节的读取,则比较耗费时间,采用BufferedReader则可以一行行的读取
			String data=null;
			try {
				while((data=bfr.readLine())!=null){
					System.out.println(data);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

 二、上面是读取文件的两种方法,下面插入写入文件的方法,

	File file=new File(str);
		try {
			FileOutputStream fop=new FileOutputStream(file);  //创建输出流对象
			String s="hello,word!";
			byte[] b=new byte[1024];
			b=s.getBytes();    //将String类型的s字符串以字符的形式赋给字节数组
			try {
				fop.write(b, 0, b.length);
				fop.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

 三、复制文件方法

			try {
			FileInputStream fip=new FileInputStream(str1);
			FileOutputStream fop=new FileOutputStream(str2);
			BufferedReader bfr=new BufferedReader(new InputStreamReader(fip));
			String s=null;
			while((s=bfr.readLine())!=null){
				byte[] b=new byte[1024];
				b=s.getBytes();
				fop.write(b, 0, b.length);
			}
			fop.close();
			bfr.close();
		} catch (FileNotFoundException e) {
			// TODO: handle exception
			System.out.println("没有找到文件!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

猜你喜欢

转载自1576610638.iteye.com/blog/2205623