私は複数のドキュメントから選択して新しいファイルを作成するデータがある場所にプログラムを作成しています。毎回新しくファイルにデータを書き込む
以下は私のコードです。
public class IndexFiles extends SwingWorker<Void, String> {
private String inputPath;
public IndexFiles(String inputPath) {
this.inputPath = inputPath;
}
@Override
protected Void doInBackground() throws Exception {
File directory = new File(inputPath);
countFilesInDirectory(directory);
return null;
}
void countFilesInDirectory(File directory) throws IOException {
System.out.println("entered");
File[] list = directory.listFiles();
System.out.println("length is " + list.length);
for (int i = 0; i < list.length; i++) {
GenerateFiles(list[i].getAbsoluteFile().toString());
}
}
private void GenerateFiles(String inputfilePath) throws IOException {
String input = inputfilePath;
URL url = new URL("file:///" + input);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
String tempPath = inputfilePath.substring(0, inputfilePath.lastIndexOf("\\") + 1);
String secPath = tempPath.substring(0, tempPath.lastIndexOf("\\"));
String finalPath = secPath.substring(0, secPath.lastIndexOf("\\")) + "\\OP\\";
File outPath = new File(finalPath);
if (!outPath.exists()) {
outPath.mkdir();
}
File temp = new File(finalPath + "temp.txt");
FileOutputStream fos = new FileOutputStream(temp, true);
if (!temp.exists()) {
temp.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("");
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("/section")) {
break;
}
if (inputLine.contains("DOCTYPE")) {
inputLine = inputLine.replace("<!DOCTYPE html>", "");
}
if (inputLine.contains("html")) {
inputLine = inputLine.replaceAll(
"<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"content-type\" content=\"text/html\" charset=\"utf-8\"/>(.*)<section>",
"");
}
if (inputLine.contains("?")) {
inputLine = inputLine.replace("<?", "");
}
if (inputLine.contains("pb")) {
inputLine = inputLine.replaceAll("pb label=\"(.*)\"?>", "");
}
if (!(inputLine.trim().isEmpty())) {
bw.append(inputLine);
bw.newLine();
}
}
bw.close();
in.close();
}
}
このプログラムは初めて正常に動作します。ファイルが正しく作成されています。しかし、この問題を再び実行すると、新しい新しいデータを作成する代わりに、問題が追加されます。私はこれがFileOutputStream fos = new FileOutputStream(temp, true);
のためだと確信しています。true
を削除すると、ファイルが完成するたびに新しいコピーが更新されます。しかし、私の必要条件は、プログラムを実行するたびに新しいデータを作成し、既存のデータに追加するのではなく、新しいデータを作成することです。
私は10ファイルと言って、プログラムを実行すると、10ファイルすべての内容が一時ファイルに格納されます。私は再びそれを実行する、それはのようにする必要があります、私は一時ファイルをクリアします。これらの10個のファイルの内容を書きます。しかし、今、私はプログラムを実行し、データは一時ファイルに書き込まれ、私は再びそれを実行する、それは同じ10ファイルのデータが追加されます。私は完全なコンテンツを置き換えたいが、個々のファイルのコンテンツは置き換えたくない。最初に実行すると、10ファイルのデータが一時ファイルに書き込まれます。私は再びそれを実行する、一時ファイルをクリアし、この10ファイルのデータを書き込む必要があります。
どうすればいいのか教えてください。
おかげ
[Javaが既存の出力ファイルを上書きする]の重複(http://stackoverflow.com/questions/17957849/java-overwriting-an-existing-output-file)? –
問題は同じファイル名であると思います。ファイル名にタイムスタンプを追加してみてください。毎回新しいファイルを作成します。 – sAm
こんにちは@TomRees、そうではありません。私は明確に上記の問題を述べました。 – Rakesh