Java中文件读写

IO类图如下:(重要记住)


1.File类

①File类对文件系统进行操作。

②File类与FileInputStream类的区别:流类关注的是文件内容,而File类关注的是文件在磁盘上的存储。

字节流读出的是byte[],字符流读出的是char或String。

2. 流程

file(内存)-->输入流-->程序-->输出流-->file(内存)

当我们读写文本文件的时候,采用Reader是非常方便的,比如FileReader、InputStreamReader和BufferedReader。其中最重要的类是InputStreamReader,它是字节转换为字符的桥梁。

例:

package fileDemo;

import java.io.BufferedReader;
import java.io.FileReader;

public class Main_file {

	public static void main(String[] args) {
		FileReader fr;
		BufferedReader br;
		String s;
		String []sArray;
		try {
			fr = new FileReader("f:\\1a.txt");
			br = new BufferedReader(fr);
			s = br.readLine();
			sArray = s.split("\\s+");
			for(int i=0;i<sArray.length;i++){
				System.out.println(sArray[i]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

备注:

①为了达到更高的效率,可以考虑在BufferedReader内包装InputStreamReader。例如:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

②最后要记得输入输出流的关闭;

3. RandomAccessFile类

Java的RandomAccessFile提供对文件的读写功能,与普通的输入输出流不一样的是RamdomAccessFile可以任意的访问文件的任何地方。这就是“Random”的意义所在。

RandomAccessFile的对象包含一个记录指针,用于标识当前流的读写位置,这个位置可以向前移动,也可以向后移动。RandomAccessFile包含两个方法来操作文件记录指针。

long getFilePoint():记录文件指针的当前位置。

void seek(long pos):将文件记录指针定位到pos位置。

RandomAccessFile包含InputStream的三个read方法,也包含OutputStream的三个write方法。同时RandomAccessFile还包含一系列的readXxx和writeXxx方法完成输入输出。

但该类的读写速率较其他的慢很多。

例:

package fileDemo;

import java.io.File;
import java.io.RandomAccessFile;

public class Main_file {

	public static void main(String[] args) {
		File file = new File("f:\\1a.txt");
		RandomAccessFile randomFile = null;
		try {
			randomFile = new RandomAccessFile(file, "r");
			long fileLength = randomFile.length();
			int beginIndex = fileLength>4?4:0;
			randomFile.seek(beginIndex);
			byte[] bytes = new byte[10];
			int byteread = 0;
			while((byteread=randomFile.read(bytes))!=-1){
				System.out.write(bytes,0,byteread);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally{
			if(randomFile!=null){
				try{
					randomFile.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
}

4. 创建目录或文件

4.1 判断文件夹是否存在,不存在创建文件夹

File file =new File(path+filename);   
//如果文件夹不存在则创建   
if  (!file .exists())     
{     
    file .mkdir();   
}     

4.2 判断文件是否存在,不存在创建文件

File file=new File(path+filename);   
    if(!file.exists())   
    {   
        try {   
            file.createNewFile();   
        } catch (IOException e) {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
        }   
    }    

参考:http://blog.youkuaiyun.com/jiangxinyu/article/details/7885518/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值