条件是,如果目录存在,则必须在该特定目录中创建文件而不创建新目录。
以下代码仅创建具有新目录但不适用于现有目录的文件。例如,目录名称就像" 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();
答案 0 :(得分:94)
此代码首先检查目录是否存在,否则创建目录,然后创建文件。请注意,我无法验证您的某些方法调用,因为我没有完整的代码,所以我假设调用getTimeStamp()
和getClassName()
之类的内容将工作。您还应该对使用任何IOException
类时可能引发的java.io.*
做一些事情 - 写入文件的函数应抛出此异常(并在其他地方处理),或者您应该直接在方法中做到这一点。另外,我假设id
属于String
类型 - 我不知道您的代码没有明确定义它。如果它是int
之类的东西,你可能应该把它转换为String
,然后像在这里一样在fileName中使用它。
此外,我根据我认为合适的情况,将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
,包括目录已存在的情况。
答案 1 :(得分:15)
我建议Java8 +使用以下内容。
/**
* Creates a File if the file does not exist, or returns a
* reference to the File if it already exists.
*/
private File createOrRetrieve(final String target) throws IOException{
final Path path = Paths.get(target);
if(Files.notExists(path)){
LOG.info("Target file \"" + target + "\" will be created.");
return Files.createFile(Files.createDirectories(path)).toFile();
}
LOG.info("Target file \"" + target + "\" will be retrieved.");
return path.toFile();
}
/**
* Deletes the target if it exists then creates a new empty file.
*/
private File createOrReplaceFileAndDirectories(final String target) throws IOException{
final Path path = Paths.get(target);
// Create only if it does not exist already
Files.walk(path)
.filter(p -> Files.exists(p))
.sorted(Comparator.reverseOrder())
.peek(p -> LOG.info("Deleted existing file or directory \"" + p + "\"."))
.forEach(p -> {
try{
Files.createFile(Files.createDirectories(p));
}
catch(IOException e){
throw new IllegalStateException(e);
}
});
LOG.info("Target file \"" + target + "\" will be created.");
return Files.createFile(
Files.createDirectories(path)
).toFile();
}
答案 2 :(得分:11)
尽量使其尽可能简短。创建目录(如果该目录不存在),然后返回所需的文件:
/** 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);
}
答案 3 :(得分:4)
<强>码强>
// 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);
}
答案 4 :(得分:1)
使用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);
}
答案 5 :(得分:0)
如果创建基于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;
}
答案 6 :(得分:0)
java 8+版本
CLASS TC_B definition for testing.
private:
METHODS: M_B
IMPORTING cut TYPE REF TO CL_A.
METHOD M_B.
cut->M_A().
ENDMETHOD.
CLASS LCL_B definition deferred.
CLASS TC_B definition local friends LCL_B.
CLASS LCL_B definition final for testing.
private:
DATA: cut TYPE REF TO CL_A.
env TYPE REF TO TC_B.
METHODS: test_M_A for testing,
setup.
METHOD setup.
CREATE OBJECTS cut, env.
ENDMETHOD.
METHOD test_M_A.
env->M_B( cut ).
ENDMETHOD.
Files.createDirectories
创建一个新目录和不存在的父目录。
如果目录已经存在,则该方法不会引发异常。