条件是如果目录存在,则必须在该特定目录中创建文件,而不创建新目录。
下面的代码仅在新目录中创建文件,而不是在现有目录中创建文件。例如,目录名称类似于“GETDIRECTION”:
String PATH = "/remote/dir/server/";
String fileName = PATH.append(id).concat(getTimeStamp()).append(".txt");
String directoryName = PATH.append(this.getClassName());
File file = new File(String.valueOf(fileName));
File directory = new File(String.valueOf(directoryName));
if (!directory.exists()) {
directory.mkdir();
if (!file.exists() && !checkEnoughDiskSpace()) {
file.getParentFile().mkdir();
file.createNewFile();
}
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value);
bw.close();
Java 8+ 版本:
import java.nio.file.Paths;
import java.nio.file.Files;
Files.createDirectories(Paths.get("/Your/Path/Here"));
Files.createDirectories()
创建一个新目录和不存在的父目录。如果目录已经存在,此方法不会抛出异常。
此代码首先检查目录是否存在,如果不存在则创建它,然后创建文件。请注意,我无法验证您的某些方法调用,因为我没有完整的代码,因此我假设对
getTimeStamp()
和 getClassName()
等内容的调用会起作用。您还应该对使用任何 IOException
类时可能抛出的 java.io.*
进行一些操作 - 写入文件的函数应该抛出此异常(并在其他地方处理),或者您应该在直接用方法。另外,我假设 id
属于 String
类型 - 我不知道,因为您的代码没有明确定义它。如果它是像 int
这样的其他东西,您可能应该将其转换为 String
,然后再在文件名中使用它,就像我在这里所做的那样。
此外,我将您的
append
通话替换为 concat
或 +
,因为我认为合适。
public void writeFile(String value){
String PATH = "/remote/dir/server/";
String directoryName = PATH.concat(this.getClassName());
String fileName = id + getTimeStamp() + ".txt";
File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}
File file = new File(directoryName + "/" + fileName);
try{
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value);
bw.close();
}
catch (IOException e){
e.printStackTrace();
System.exit(-1);
}
}
如果您想在 Microsoft Windows 上运行代码,您可能不应该使用这样的裸路径名 - 我不确定它将如何处理文件名中的
/
。为了实现完全的可移植性,您可能应该使用类似 File.separator 的东西来构建您的路径。
编辑:根据下面JosefScript的评论,没有必要测试目录是否存在。如果创建了目录,则
directory.mkdir()
调用将返回 true
,如果没有,则返回 false
,包括目录已存在的情况。
尝试使其尽可能简短。如果目录不存在则创建,然后返回所需的文件:
/** Creates parent directories if necessary. Then returns file */
private static File fileWithDirectoryAssurance(String directory, String filename) {
File dir = new File(directory);
if (!dir.exists()) dir.mkdirs();
return new File(directory + "/" + filename);
}
我建议 Java8+ 以下。
/**
* Creates a File if the file does not exist, or returns a
* reference to the File if it already exists.
*/
public File createOrRetrieve(final String target) throws IOException {
final File answer;
Path path = Paths.get(target);
Path parent = path.getParent();
if(parent != null && Files.notExists(parent)) {
Files.createDirectories(path);
}
if(Files.notExists(path)) {
LOG.info("Target file \"" + target + "\" will be created.");
answer = Files.createFile(path).toFile();
} else {
LOG.info("Target file \"" + target + "\" will be retrieved.");
answer = path.toFile();
}
return answer;
}
编辑:更新以修复@Cataclysm 和@Marcono1234 指出的错误。谢谢大家:)
java.nio.Path
public static Path createFileWithDir(String directory, String filename) {
File dir = new File(directory);
if (!dir.exists()) dir.mkdirs();
return Paths.get(directory + File.separatorChar + filename);
}
代码:
// Create Directory if not exist then Copy a file.
public static void copyFile_Directory(String origin, String destDir, String destination) throws IOException {
Path FROM = Paths.get(origin);
Path TO = Paths.get(destination);
File directory = new File(String.valueOf(destDir));
if (!directory.exists()) {
directory.mkdir();
}
//overwrite the destination file if it exists, and copy
// the file attributes, including the rwx permissions
CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
Files.copy(FROM, TO, options);
}
如果您创建基于 Web 的应用程序,更好的解决方案是检查目录是否存在,如果不存在则创建文件。如果存在,则重新创建。
private File createFile(String path, String fileName) throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(".").getFile() + path + fileName);
// Lets create the directory
try {
file.getParentFile().mkdir();
} catch (Exception err){
System.out.println("ERROR (Directory Create)" + err.getMessage());
}
// Lets create the file if we have credential
try {
file.createNewFile();
} catch (Exception err){
System.out.println("ERROR (File Create)" + err.getMessage());
}
return file;
}
使用 Java 8 的简单解决方案
public void init(String multipartLocation) throws IOException {
File storageDirectory = new File(multipartLocation);
if (!storageDirectory.exists()) {
if (!storageDirectory.mkdir()) {
throw new IOException("Error creating directory.");
}
}
}
如果您使用的是 Java 8 或更高版本,那么
Files.createDirectories()
方法效果最好。