java io流清空txt文件内容及填充文件内容

该博客介绍了如何使用Java的IO流来清空一个TXT文件的内容,并填充新的数据。首先,通过File类获取文件路径,然后使用FileWriter在追加模式下写入信息,包括加密后的IP、数据库名、用户名和密码。接着,提供了一个`clearInfoForFile`方法,用于清空指定文件的内容。最后,展示了读取文件内容的代码片段。

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

File file = new File(this.getClass().getResource("").getPath());
System.out.println(file.getPath());
String path=file.getPath();
String filename="test1.txt";
//path=path.substring(0,path.indexOf("WEB-INF"))+"upload\\Excel"+"\\"+"import.txt";  //服务器专用
      username= DesUtil.encrypt(username);
      password=DesUtil.encrypt(password);
      ip=DesUtil.encrypt(ip);
      DatabaseName=DesUtil.encrypt(DatabaseName);
path=path.substring(0,path.indexOf("target"))+"src\\main\\webapp\\upload\\Excel"+"\\"+"import.txt";
clearInfoForFile(path);
try {
      FileWriter fileWriter =new FileWriter(path, true);
      String info="";
      info=info+ip+"\n"+DatabaseName+"\n"+username+"\n"+password;
      fileWriter.write(info);
      fileWriter.flush();
      fileWriter.close();
}catch (IOException e){

}
InputStream is = new FileInputStream(path);
String line; // 用来保存每行读取的内容
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
line = reader.readLine(); // 读取第一行
int t=0;
if (line==null){

}else {
   t=1;
}
reader.close();
is.close();

//清空文件内容
public  void clearInfoForFile(String fileName) {
   File file =new File(fileName);
   try {
      if(!file.exists()) {
         file.createNewFile();
      }
      FileWriter fileWriter =new FileWriter(file);
      fileWriter.write("");
      fileWriter.flush();
      fileWriter.close();
   } catch (IOException e) {
      e.printStackTrace();
   }
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值