Java文件读写

文件写入:

        // 写入数据保存在本地D:/user/error/目录下
	private void write() {
               //获取系统毫秒数
               long currentTimeMillis = System.currentTimeMillis();
		String ts = String.valueOf(currentTimeMillis);
		// 文件名称系统毫秒数
		String filepath = "D:/user/error/" + String.valueOf(currentTimeMillis) + ".txt";
		File file = new File(filepath);
		//判断文件是否存在,不存在则创建
		if (!file.exists()) {
			file.getParentFile().mkdirs();
		}
		OutputStreamWriter opw;
		try {
			opw = new OutputStreamWriter(new FileOutputStream(filepath), "GBK");
			BufferedWriter bufw = new BufferedWriter(opw);
			bufw.write("写入数据123456");
			bufw.close();
			opw.close();
		} catch (Exception e) {
			
			e.printStackTrace();
		}

	}

  文件读取:

public  void read() {

		String filepath = "D:/user/error/";
		File file = new File(filepath);
                //获取D:/user/error/目录下所有文件
		File[] files = file.listFiles();
		Arrays.sort(files);
		String read = "";
		try {
			for (int i = 0; i < files.length; i++) {
				if (files[i].isFile()) {
					InputStreamReader opw = new InputStreamReader(new FileInputStream(files[i]), "GBK");
					BufferedReader bufr = new BufferedReader(opw);
					read = bufr.readLine();
					bufr.close();
					System.out.println(read);
                                        //删除当前文件
					files[i].delete();
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}                

  

转载于:https://www.cnblogs.com/staticking/p/9044204.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值