Java创建文件夹及文件 .
分类: java 江湖Study 2013-04-17 15:53 3068人阅读 评论(1) 收藏 举报
[java] view plaincopyprint?
01.package com.xhkj.util;
02.
03.import java.io.File;
04.import java.io.IOException;
05.
06.public class CreateFileUtil {
07.
08.public static boolean CreateFile(String destFileName) {
09. File file = new File(destFileName);
10. if (file.exists()) {
11. System.out.println("创建单个文件" + destFileName + "失败,目标文件已存在!");
12. return false;
13. }
14. if (destFileName.endsWith(File.separator)) {
15. System.out.println("创建单个文件" + destFileName + "失败,目标不能是目录!");
16. return false;
17. }
18. if (!file.getParentFile().exists()) {
19. System.out.println("目标文件所在路径不存在,准备创建。。。");
20. if (!file.getParentFile().mkdirs()) {
21. System.out.println("创建目录文件所在的目录失败!");
22. return false;
23. }
24. }
25.
26. // 创建目标文件
27. try {
28. if (file.createNewFile()) {
29. System.out.println("创建单个文件" + destFileName + "成功!");
30. return true;
31. } else {
32. System.out.println("创建单个文件" + destFileName + "失败!");
33. return false;
34. }
35. } catch (IOException e) {
36. e.printStackTrace();
37. System.out.println("创建单个文件" + destFileName + "失败!");
38. return false;
39. }
40.}
41.
42.
43.
44.public static boolean createDir(String destDirName) {
45. File dir = new File(destDirName);
46. if(dir.exists()) {
47. System.out.println("创建目录" + destDirName + "失败,目标目录已存在!");
48. return false;
49. }
50. if(!destDirName.endsWith(File.separator))
51. destDirName = destDirName + File.separator;
52. // 创建单个目录
53. if(dir.mkdirs()) {
54. System.out.println("创建目录" + destDirName + "成功!");
55. return true;
56. } else {
57. System.out.println("创建目录" + destDirName + "成功!");
58. return false;
59. }
60.}
61.
62.
63.
64.public static String createTempFile(String prefix, String suffix, String dirName) {
65. File tempFile = null;
66. try{
67. if(dirName == null) {
68. // 在默认文件夹下创建临时文件
69. tempFile = File.createTempFile(prefix, suffix);
70. return tempFile.getCanonicalPath();
71. }
72. else {
73. File dir = new File(dirName);
74. // 如果临时文件所在目录不存在,首先创建
75. if(!dir.exists()) {
76. if(!CreateFileUtil.createDir(dirName)){
77. System.out.println("创建临时文件失败,不能创建临时文件所在目录!");
78. return null;
79. }
80. }
81. tempFile = File.createTempFile(prefix, suffix, dir);
82. return tempFile.getCanonicalPath();
83. }
84. } catch(IOException e) {
85. e.printStackTrace();
86. System.out.println("创建临时文件失败" + e.getMessage());
87. return null;
88. }
89.}
90.
91.
92.public static void main(String[] args) {
93. // 创建目录
94. String dirName = "c:/test/test0/test1";
95. CreateFileUtil.createDir(dirName);
96. // 创建文件
97. String fileName = dirName + "/test2/testFile.txt";
98. CreateFileUtil.CreateFile(fileName);
99. // 创建临时文件
100. String prefix = "temp";
101. String suffix = ".txt";
102. for(int i = 0; i < 10; i++) {
103. System.out.println("创建了临时文件:" + CreateFileUtil.createTempFile(prefix, suffix, dirName));
104. }
105.
106.}
107.
108.}