此代码首先检查目录是否存在,如果不存在则创建该目录,然后创建该文件。请注意,由于我没有完整的代码,因此我无法验证您的某些方法调用,因此,我假设对
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之](http://codingdict.com/questions/121409类的东西来构建路径。
编辑
:根据下面的Josefscript评论,没有必要测试目录是否存在。该
directory.mkdir()
调用将返回
true如果它创建一个目录,
false如果没有,包括在这个目录已经存在的情况下。



