此代码首先检查目录的存在,如果没有,则创建它,然后创建该文件.请注意,我无法验证一些方法调用,因为我没有完整的代码,所以我假设调用getTimeStamp()和getClassName()可以工作.您还应该在使用任何java.io. *类时抛出可能的IOException异常 – 您写入文件的函数应该抛出此异常(并在其他地方处理),或者您应该在该方法直接.此外,我认为id是String类型 – 我不知道你的代码没有明确定义它.如果它是一个类似于int的东西,那么在文件名中使用它之前,你应该把它转换成一个String,就像我在这里做的那样.
另外,我用concat或者我认为适当的替换了你的append电话.
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,包括目录已存在的情况.