您好我正在尝试操作文件(将temp复制到orig。)但是每当我尝试第二次打开transaction_sales.dat文件时,似乎存在问题(访问被拒绝)。我该怎么办? :(((
public static void writeFile() {
Path file = null;
Path file2 = null;
OutputStream output = null;
BufferedWriter writer = null;
InputStream input = null;
BufferedReader reader = null;
String[] strReaderAssign = new String[10000]; // for reading files
String strReader = null;
int strike = 0; // counter
try { // UNFINISHED
file = Paths.get("transaction_sales.dat");
output = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
writer = new BufferedWriter(new OutputStreamWriter(output));
input = new BufferedInputStream(Files.newInputStream(file));
reader = new BufferedReader(new InputStreamReader(input));
if(reader.readLine() == null) { // if file is empty
writer.write(strHolder, 0, strHolder.length()); // writes to file
writer.close(); // closes file
reader.close(); // closes read file
}
else { // write to temporary file
file = Paths.get("transaction_sales.dat");
file2 = Paths.get("transaction_sales_temp.dat"); // temporary file
output = new BufferedOutputStream(Files.newOutputStream(file2));
writer = new BufferedWriter(new OutputStreamWriter(output));
writer.write((strHolder), 0, strHolder.length()); // writes to temp file
for(int i = 0; i < 10; i++) {
writer.newLine(); // writes new line to file 10x
}
writer.close(); // closes file
try {
file = Paths.get("transaction_sales.dat"); // re-reads updated data in a file
input = new BufferedInputStream(Files.newInputStream(file));
reader = new BufferedReader(new InputStreamReader(input));
while((strReader = reader.readLine()) != null) {
strReaderAssign[strike] = strReader; // assigns to array
strike++; // increment
}
strike = 0; // resets value
reader.close(); // closes file
// appends file
output = new BufferedOutputStream(Files.newOutputStream(file2, APPEND));
writer = new BufferedWriter(new OutputStreamWriter(output));
for(int j = 0; (strReaderAssign[j] != null); j++) {
writer.write(strReaderAssign[j]);
writer.newLine();
}
// resets value
for(int j = 0; j < strReaderAssign.length; j++) {
strReaderAssign[j] = null;
}
writer.close(); // closes file
file = Paths.get("transaction_sales.dat");
file2 = Paths.get("transaction_sales_temp.dat");
Files.copy(file2, file, REPLACE_EXISTING);
Files.delete(file);
}
catch(IOException d) {
System.out.println(d.getMessage());
}
}
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}