工作周结之读写文件

一、读取文件

有两种方式,一是从缓冲流里读,一种是Scanner读取。前者是读取普通文件,先获取全部内容到缓冲流里,然后依次读取。后者适合读取大文件,读一行,取一行。推荐后者

/**
	 * 通过缓冲流读取文件
	 * @param path
	 */
	public static  void normal(String path){
		File file = new File(path);
		if(file.exists()&&file.isFile()){
			try {
				InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
				BufferedReader buf = new BufferedReader(reader);
				String line = "";
				try {
					while((line = buf.readLine())!=null){
						System.out.println(line);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			
		}
	}
	
	/**
	 * 通过Scanner读取大文件
	 * @param path
	 */
	public static  void bigFileRead(String path){
		File file = new File(path);
		try {
			FileInputStream in = new FileInputStream(file);
			Scanner scan = new Scanner(in,"UTF-8");
			while(scan.hasNextLine()){
				String line = scan.nextLine();
				System.out.println(line);
			}
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		
	}

二、写文件

写文件同样有两种方式,覆盖式写入和追加式写入。前者是写过一次后,再次写入,这次所写的内容会覆盖掉之前的内容。后者是写过一次后,再次写入,这次所写的内容会追加到之前内容的后面,之前的内容依旧存在。推荐使用后者。

/**
	 * 再次写入内容会覆盖掉之前的内容,慎用!!!
	 * 
	 * @param file
	 * @param str
	 */
	public static void replaceWrite(File file, String str) {
		// 创建一个空文件
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// 写入内容
		if (file.isFile() && file.length() == 0) {
			try {
				FileOutputStream out = new FileOutputStream(file);
				PrintStream p = new PrintStream(out);
				p.print(str);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

	}
	
	/**
	 * 此方法是追加写入内容的,不会覆盖之前写入的内容,推荐使用!!
	 * @param file
	 * @param str
	 */
	public static void appendWrite(File file,String str){
		//创建一个空文件
		if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//写入内容
		try {
			BufferedWriter out = new BufferedWriter(new FileWriter(file,true));
			out.write(str);
			out.write("\r\n");//换行
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值