和删除指定目录及子目录下名叫“xxx.txt”的所有文件一样,也是使用递归的方式实现的。
代码如下:
public class Example826003 { private static FileOutputStream out; /**
* @param args 指定目录下及子目录下添加指定的文件
*/
public static void main(String[] args) {
String dir = "D:\\PCsync\\python";
File file= new File(dir);
circleMethod(file);
System.out.println("文件创建成功!"); } private static void circleMethod(File file) {
// TODO Auto-generated method stub
if (file.isDirectory()) {
createFile(file);
File[] fileList = file.listFiles();
for (int i = 0; i < fileList.length; i++) {
circleMethod(fileList[i]);
}
}
} private static void createFile(File file) {
// TODO Auto-generated method stub
String nameDir = file.getAbsoluteFile()+File.separator+"111.txt"; try {
out = new FileOutputStream(nameDir);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str= "xxxx";
byte[] b =str.getBytes();
for (int i = 0; i < b.length; i++) {
try {
out.write(b[i]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }