Я хочу прочитать входящий файл, полученный в папке, и сохранить содержимое нового файла, полученного в базу данных.readAllBytes(). FileSystemException: процесс не может получить доступ к файлу, потому что он используется другим процессом.
Я смоделировал это, скопировав один файл «a.txt» сначала и «j.txt» после.
У меня ошибка, показанная ниже.
Ошибка
Created: a.txt
1
Created: j.txt
java.nio.file.FileSystemException: C:\Users\khunpaen\folder\j.txt: The process cannot access the file because it is being used by another process.
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.Files.readAllBytes(Unknown Source)
Коды
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.sql.DriverManager;
import com.mysql.jdbc.PreparedStatement;
public class FileWatch {
private WatchService watcher = null;
private Path p;
private WatchKey watchKey;
private int count;
String fileName;
public FileWatch() {
String comName = System.getProperty("user.name");
p = Paths.get("C:/Users/"+comName+"/folder");
try {
watcher = FileSystems.getDefault().newWatchService();
watchKey = p.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
// repeat forever
for (;;)
{
watchKey = watcher.take();
for (WatchEvent<?> event : watchKey.pollEvents())
{
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("Created: " + event.context().toString());
fileName = event.context().toString();
}
String content = read("C:/Users/"+comName+"/folder/"+fileName, StandardCharsets.UTF_8);
//System.out.println(content);
count = insert(event.context().toString(),content);
System.out.println(count);
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
}
watchKey.reset();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int insert(String s,String b) {
int a = 0;
try {
//connect to database
java.sql.Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","abcd");
// the mysql insert statement
String query = " insert into details (email,text)"
+ " values (?,?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = (PreparedStatement) myConn.prepareStatement(query);
preparedStmt.setString(1, s);
preparedStmt.setString(2, s);
// execute the preparedstatement
a = preparedStmt.executeUpdate();
}
catch(Exception e) {
e.printStackTrace();
}
return a;
}
public String read(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}
Возможно, это поможет вам? http://stackoverflow.com/questions/26741191/ioexception-the-process-cannot-access-the-file-file-path-because-it-is-being –
Есть ли какой-либо другой процесс, о котором вы можете подумать, есть блокировка в файле 'j.txt'? Ошибка, которую вы получаете, по сути говорит вам, что у другого процесса есть блокировка этого файла. –