1

I want to read incoming file received in a folder and store the contents of the new file received into a database.

I simulated this by copying one file "a.txt" first and "j.txt" after.

I got the error shown below.

Error

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)

Codes

    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);
    }
}
user3820292
  • 310
  • 3
  • 19
  • 1
    May be this will helps you ? http://stackoverflow.com/questions/26741191/ioexception-the-process-cannot-access-the-file-file-path-because-it-is-being – Jean-Baptiste Yunès Jul 03 '15 at 05:42
  • Is there any other process of which you can think which might have a lock on the `j.txt` file? The error you are getting is essentially telling you that another process has a lock on this file. – Tim Biegeleisen Jul 03 '15 at 05:42

1 Answers1

0

Your code is broken, for a start. You're trying to read a file every time

  • (a) a file is created
  • (b) a file is modified
  • (c) a file is deleted
  • (d) there is an event overflow.

    1. On Windows it is guaranteed you will get this exception on (a) or (b).
    2. You will always get FileNotFoundException on (c).
    3. You will read some arbitrary file left over from last time on (b) (c) or (d), because your filename variable is incorrectly scoped and you're executing the read() method unconditionally.

You'll have to figure out some way to wait until the file is closed before you attempt to read it.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Not only that but there is also the db connection problem which is _also_ reopened every time – fge Jul 03 '15 at 06:16
  • And by the way, on c. you won't get `FileNotFoundException` but `NoSuchFileException` – fge Jul 03 '15 at 06:17