I'm working on a console App using Java 1.8 that will read JSON files from a directory. Each file will be processed and then moved to another folder. My problem is the error you see in the title of this question.
This is my function to list all the files in the folder
public static void search(final String pattern, final File folder, List<String> result) {
for (final File f : folder.listFiles()) {
if (f.isDirectory()) {
search(pattern, f, result);
}
if (f.isFile()) {
if (f.getName().matches(pattern)) {
if(f.length() > 0) {
result.add(f.getAbsolutePath());
}
}
}
}
}
This is my function to read the file string
static String readFile(String path, Charset encoding) throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
This is my function to move the file:
private static void moveFile(String filename){
String pathFrom = moveFilesFrom + filename;
String pathTo = moveFilesTo + filename;
try {
Files.move(Paths.get(pathFrom), Paths.get(pathTo));
} catch (IOException e) {
log.error("Failed to move file from " + pathFrom + " to " + pathTo);
e.printStackTrace();
}
}
And finally how I consume these files. result
is a List<String>
returned from search
:
for (String jsonFile : result) {
try {
String jsonString = readFile(jsonFile, Charset.defaultCharset());
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(jsonString);
JSONArray data = (JSONArray) jsonObject.get("data");
long linesAdded = processLines(data);
totalItemsInserted = totalItemsInserted + linesAdded;
File f = new File(jsonFile);
//System.out.println("File "+ f.getName() +" added " + linesAdded + " items. Curent Total:" + totalItemsInserted);
log.info("File "+ f.getName() +" has "+ data.size() +"items and added " + linesAdded + " items. Curent Total:" + totalItemsInserted);
if(moveFiles){
moveFile(f.getName());
}
} catch (IOException | ParseException | java.text.ParseException e) {
e.printStackTrace();
}
}
How can I change my code to avoid this error, and if there is a way for me to unlock the files.