我想在一个单独的线程上读出一个文件,之后我想将文件移动到一个新目录,但编译器一直告诉我,我无法移动该文件,因为它被另一个进程使用。我已多次检查它并且我的读者已关闭,我使用join()
函数等到readThread
完成了这可能是什么?
public class CallLogReader extends Thread {
private Path path;
private LinkedList<CallLog> callLogs;
public CallLogReader(Path path){
setPath(path);
callLogs = new LinkedList<>();
}
public Path getPath() {
return path;
}
public void setPath(Path path) {
this.path = path;
}
public LinkedList<CallLog> getCallLogs() {
return callLogs;
}
@Override
public void run(){
FileReader reader = null;
BufferedReader buffReader = null;
try{
reader = new FileReader(path.toFile());
buffReader = new BufferedReader(reader);
String currentLine = buffReader.readLine();
while(currentLine != null){
String[] dataBlocks = currentLine.split(";");
if(!dataBlocks[7].equals("IGNORE")){
callLogs.add(new CallLog(Integer.parseInt(dataBlocks[0]) ,dataBlocks[1], ConvertStringToDate(dataBlocks[2], dataBlocks[3]), dataBlocks[4], dataBlocks[5], Integer.parseInt(dataBlocks[6]), dataBlocks[7]));
}
currentLine = buffReader.readLine();
}
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
finally{
try{
if(buffReader != null){
buffReader.close();
}
if(reader != null){
reader.close();
}
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
}
}
private LocalDateTime ConvertStringToDate(String dateString,String timeString){
String dateTimeString = dateString + " " + timeString;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
return LocalDateTime.parse(dateTimeString,formatter);
}
public void moveFile(){
Path newPath = Paths.get(path.getParent().getParent().toString() + "\\processed\\" + path.getFileName());
try{
Files.move(path,newPath,StandardCopyOption.REPLACE_EXISTING);
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Path path_1 = Paths.get("C:\\Users\\11601037\\Desktop\\resources\\in\\testdata1.csv");
CallLogReader reader_1 = new CallLogReader(path_1);
reader_1.run();
try{
reader_1.join();
}
catch(InterruptedException ex){
System.out.println(ex.getMessage());;
}
reader_1.moveFile();
System.out.println(path_1.getParent().getParent().toString());
}
}