一种对文件读取和写入数据的方法

本文介绍了使用Java进行文件读写的两种常见方法:从固定路径读取文件内容及按日期结构写入文件。通过实例展示了如何利用FileInputStream与BufferedReader读取JSON文件,以及如何结合Calendar与SimpleDateFormat生成带时间戳的文件名,并使用FileOutputStream与BufferedWriter将数据写入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

10.读取固定路径下的文件的一种方法:
	private static String getJson() throws Exception {
FileInputStream inputStream = new FileInputStream("c://video.json");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
String str = "";
StringBuffer json = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
			json.append(str);
		}
		bufferedReader.close();
		inputStream.close();
		return json.toString();
	}
11.将数据写入一个已知的文件中:
int year = Calendar.getInstance().get(Calendar.YEAR);
int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
Date date=new Date();
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
String currenttime=simpleDateFormat.format(date);
String jsondataPath=year+"/"+month+"/"+day;
//String jsondataPath = "D://" + year + "//" + month + "//" + day;
String filename = currenttime + ".json";
	先创建文件夹,然后开始读写操作,
   File file = new File(jsondataPath);
				if (!file.exists()) {
					file.mkdirs();
				}
	File file2 = new File(jsondataPath, filename);
				if (!file2.exists()) {
					try {
						file2.createNewFile();
					} catch (Exception e) {
						e.printStackTrace();
					}
			}
FileOutputStream writerStream = new FileOutputStream(fileEntity);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8"));
writer.write(jsondata);
writer.close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值