0

を使用してJavaでファイルを作成しています

BufferedWriter out = new BufferedWriter(new FileWriter(FileName));          
StringBuffer sb=new StringBuffer();
sb.append("\n");
sb.append("work");
out.write(sb.toString());
out.close();

しかし、このファイルはサーバーの bin フォルダー内に作成されています。ユーザー定義のフォルダー内にこのファイルを作成したいと思います。

どうすれば達成できますか。

4

2 に答える 2

1

I would like to create this file inside a user-defined folder.

The simplest approach is to specify a fully qualified path name. You could select that as a File and build a new File relative to it:

File directory = new File("/home/jon/somewhere");
File fullPath = new File(directory, fileName);
BufferedWriter writer = new BufferedWriter(
    new OutputStreamWriter(
        (new FileOutputStream(fullPath), charSet));
try {
    writer.write("\n");
    writer.write("work");
} finally {
    writer.close();
}

Note:

  • I would suggest using a FileOutputStream wrapped in an OutputStreamWriter instead of using FileWriter, as you can't specify an encoding with FileWriter
  • Use a try/finally block (or try-with-resources in Java 7) so that you always close the writer even if there's an exception.
于 2012-05-07T06:52:30.613 に答える
0

To create a file in a specific directory, you need to specify it in the file name.

Otherwise it will use the current working directory which is likely to be where the program was started from.

BTW: Unless you are using Java 1.4 or older, you can use StringBuilder instead of StringBuffer, although in this case PrintWriter would be even better.

于 2012-05-07T06:52:45.090 に答える