文件处理(如果文件存在则追加,不存在则生成多级文件夹以及txt目录)

public static void writeFile(String path,String fileName,String content) throws IOException {
File file = new File(path);
if(!file.exists()){
try {
boolean mkdirs = file.mkdirs();//按照该目录创建文件夹
if(mkdirs==true){
File filetxt = new File(fileName);
filetxt.createNewFile();//创建文件
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileWriter writer = null;
try {
writer = new FileWriter(path+"/"+fileName, true);
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
}
}
public static void main(String[] args){
try {
writeFile("D://wth/my","tu.txt","i love you");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

转载于:https://www.cnblogs.com/wth21-1314/p/9797377.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Python的shutil和os模块来完成这个任务。 首先,需要使用os模块来检查目标文件夹是否存在。如果目标文件夹不存在,则可以使用os.mkdir()函数来创建该文件夹。 然后,可以使用shutil模块的copy2()函数来将文件复制到目标文件夹中。如果目标文件夹中已经存在同名文件,则可以打开该文件并将新文件的内容追加到该文件中。 以下是示例代码: ```python import os import shutil # 源文件路径 src_file = '/path/to/source/file' # 目标文件夹路径 dst_folder = '/path/to/destination/folder' # 检查目标文件夹是否存在,如果不存在则创建 if not os.path.exists(dst_folder): os.mkdir(dst_folder) # 构造目标文件路径 dst_file = os.path.join(dst_folder, os.path.basename(src_file)) # 判断目标文件是否存在 if os.path.exists(dst_file): # 如果目标文件已经存在,则打开文件并将源文件内容追加文件末尾 with open(dst_file, 'a') as f: with open(src_file, 'r') as src_f: f.write(src_f.read()) else: # 如果目标文件不存在,则直接复制源文件到目标文件夹 shutil.copy2(src_file, dst_folder) ``` 在上面的代码中,使用os.path.basename()函数获取源文件文件名,然后使用os.path.join()函数将该文件名与目标文件夹路径拼接成目标文件的完整路径。最后,使用shutil模块的copy2()函数将源文件复制到目标文件夹中。如果目标文件已经存在,则使用open()函数打开目标文件,并将源文件内容追加文件末尾。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值