19package denoptim.files;
21import java.io.BufferedInputStream;
22import java.io.BufferedReader;
24import java.io.FileFilter;
25import java.io.FileInputStream;
26import java.io.FileOutputStream;
27import java.io.FileReader;
28import java.io.IOException;
29import java.io.OutputStream;
30import java.io.RandomAccessFile;
31import java.nio.channels.FileChannel;
32import java.nio.channels.FileLock;
33import java.nio.file.Files;
34import java.nio.file.Paths;
35import java.nio.file.StandardOpenOption;
36import java.util.ArrayList;
37import java.util.HashMap;
40import java.util.Map.Entry;
41import java.util.logging.Level;
42import java.util.zip.CRC32;
43import java.util.zip.ZipEntry;
44import java.util.zip.ZipOutputStream;
46import org.apache.commons.io.FilenameUtils;
47import org.apache.commons.io.filefilter.WildcardFileFilter;
49import com.google.gson.Gson;
51import denoptim.constants.DENOPTIMConstants;
52import denoptim.exception.DENOPTIMException;
53import denoptim.io.DenoptimIO;
54import denoptim.json.DENOPTIMgson;
55import denoptim.logging.StaticLogger;
86 int toIgnore = existingEntries.size() + 1 - maxSize;
88 for (Entry<File, FileFormat> e : existingEntries.entrySet())
90 if (ignored < toIgnore)
95 text = text + e.getValue() +
" " + e.getKey()
98 text = text + ff +
" " + file.getAbsolutePath();
107 +
"write list of recent files.", e);
135 boolean found =
false;
137 RandomAccessFile rafile =
null;
138 FileChannel channel =
null;
139 FileLock lock =
null;
143 rafile =
new RandomAccessFile(file,
"rw");
144 channel = rafile.getChannel();
145 lock = channel.lock();
147 for (String line; (line = rafile.readLine()) !=
null; )
149 if (line.trim().length() == 0)
151 if (line.trim().equalsIgnoreCase(query.trim()))
160 rafile.seek(channel.position());
171 if (lock !=
null && lock.isValid())
206 ArrayList<String> tmpFolders =
new ArrayList<String>();
207 tmpFolders.add(System.getProperty(
"file.separator") +
"tmp");
208 tmpFolders.add(System.getProperty(
"file.separator") +
"scratch");
209 tmpFolders.add(System.getProperty(
"java.io.tmpdir"));
211 String tmpPathName =
"";
212 String tmpFolder =
"";
213 for (String t : tmpFolders) {
215 tmpPathName = tmpFolder + System.getProperty(
"file.separator")
216 +
"Denoptim_tmpFile";
232 return (
new File(fileName)).mkdir();
242 if (fileName.length() > 0) {
243 return (
new File(fileName)).exists();
257 File f =
new File(fileName);
268 if (f.isDirectory()) {
273 boolean success = f.delete();
291 File folder =
new File(path);
292 File[] listOfFiles = folder.listFiles();
293 for (
int i = 0; i < listOfFiles.length; i++) {
294 if (listOfFiles[i].isFile()) {
295 String name = listOfFiles[i].getName();
296 if (name.contains(pattern)) {
313 BufferedInputStream bis =
null;
315 bis =
new BufferedInputStream(
new FileInputStream(fileName));
316 byte[] c =
new byte[1024];
319 while ((readChars = bis.read(c)) != -1) {
320 for (
int i = 0; i < readChars; ++i) {
327 }
catch (IOException ioe) {
334 }
catch (IOException ioe) {
350 String[] filesToZip)
throws Exception {
351 FileOutputStream fos =
new FileOutputStream(zipOutputFileName);
352 ZipOutputStream zos =
new ZipOutputStream(fos);
354 byte[] buffer =
new byte[1024];
355 CRC32 crc =
new CRC32();
356 for (
int i = 0, n = filesToZip.length; i < n; i++) {
357 String fname = filesToZip[i];
358 File cFile =
new File(fname);
359 if (!cFile.exists()) {
363 BufferedInputStream bis =
new BufferedInputStream(
364 new FileInputStream(cFile));
366 while ((bytesRead = bis.read(buffer)) != -1) {
367 crc.update(buffer, 0, bytesRead);
371 bis =
new BufferedInputStream(
new FileInputStream(cFile));
372 ZipEntry ze =
new ZipEntry(fname);
374 ze.setMethod(ZipEntry.DEFLATED);
375 ze.setCompressedSize(cFile.length());
376 ze.setSize(cFile.length());
377 ze.setCrc(crc.getValue());
378 zos.putNextEntry(ze);
379 while ((bytesRead = bis.read(buffer)) != -1) {
380 zos.write(buffer, 0, bytesRead);
403 String ext = FilenameUtils.
getExtension(inFile.getAbsolutePath());
405 if (inFile.isDirectory())
409 for(File folder : inFile.listFiles(
new FileFilter() {
412 public boolean accept(File pathname) {
413 if (pathname.isDirectory())
421 if (folder.getName().startsWith(
427 else if (folder.getName().startsWith(
439 switch (ext.toUpperCase())
487 @SuppressWarnings(
"rawtypes")
495 BufferedReader br =
null;
498 br =
new BufferedReader(
new FileReader(fileName));
499 Object o = reader.fromJson(br,Object.class);
500 Object oneObj =
null;
501 if (o instanceof ArrayList)
503 oneObj = ((ArrayList) o).get(0);
507 if (oneObj instanceof Map)
509 if (((Map)oneObj).keySet().contains(
"gVertices"))
518 catch (IOException ioe)
520 throw new IOException(
"Unable to read file '"+fileName +
"'", ioe);
532 catch (IOException ioe)
535 throw new IOException(
"Unable to close file '" + fileName +
"'",
608 Map<String,FileFormat> regexToMatch =
new HashMap<String,FileFormat>();
609 Map<String,List<FileFormat>> regexToNotMatch =
610 new HashMap<String,List<FileFormat>>();
611 String endOfSample =
null;
614 for (String regex : ff.getDefiningRegex())
616 regexToMatch.put(regex,ff);
617 if (ff.getSampleEndRegex() !=
null)
619 endOfSample = ff.getSampleEndRegex();
622 for (String regex : ff.getNegatingRegex())
624 if (regexToNotMatch.containsKey(regex))
626 regexToNotMatch.get(regex).add(ff);
628 List<FileFormat> lst =
new ArrayList<FileFormat>();
630 regexToNotMatch.put(regex, lst);
635 Map<FileFormat,Boolean> foundDefiningRegex =
new HashMap<FileFormat,Boolean>();
637 foundDefiningRegex.put(f,
false);
639 Map<FileFormat,Boolean> foundNegatingRegex =
new HashMap<FileFormat,Boolean>();
641 foundNegatingRegex.put(f,
false);
644 BufferedReader br =
null;
647 br =
new BufferedReader(
new FileReader(fileName));
649 while ((line = br.readLine()) !=
null)
651 if (endOfSample !=
null && line.matches(endOfSample))
653 break lineReadingLoop;
656 if ((line.trim()).length() == 0)
661 for (String key : regexToNotMatch.keySet())
663 if (line.toUpperCase().matches(key.toUpperCase()))
665 for (
FileFormat ff : regexToNotMatch.get(key))
667 foundNegatingRegex.put(ff,
true);
672 for (String keyRoot : regexToMatch.keySet())
674 if (line.toUpperCase().matches(keyRoot.toUpperCase()))
676 foundDefiningRegex.put(regexToMatch.get(keyRoot),
true);
681 catch (IOException ioe)
683 throw new IOException(
"Unable to read file '"+fileName +
"'", ioe);
695 catch (IOException ioe)
698 throw new IOException(
"Unable to close file '" + fileName +
"'",
706 if (foundDefiningRegex.get(ff) && !foundNegatingRegex.get(ff))
733 if (!parent.exists())
740 FileFilter fileFilter =
new WildcardFileFilter(baseName+
"*");
741 File[] cands = parent.listFiles(fileFilter);
747 int idx = i + cands.length;
748 newName =
new File(parent +
DenoptimIO.
FS + baseName +
"_" + idx);
749 if (!newName.exists())
769 List<String> sourcePathnames)
throws IOException
771 try(OutputStream out = Files.newOutputStream(
772 Paths.get(destinationPathname),
773 StandardOpenOption.CREATE,
774 StandardOpenOption.WRITE))
776 for (String sourcePathname : sourcePathnames) {
777 Files.copy(Paths.get(sourcePathname), out);
General set of constants used in DENOPTIM.
static final File RECENTFILESLIST
List of recent files.
static final String EOL
new line character
static final String GAGENDIRNAMEROOT
Prefix for generation folders.
static final String FSEIDXNAMEROOT
Prefix for graph indexing files.
static void deleteFilesContaining(String path, String pattern)
Delete all files with pathname containing a given string.
static boolean checkExists(String fileName)
static File getAvailableFileName(File parent, String baseName)
Define a filename that can be used, i.e., is still available, because no other file with the same pat...
static FileFormat detectKindOfTXTFile(String fileName)
Looks into a text file and tries to understand if the file is a known text file.
static int countLinesInFile(String fileName)
Count the number of lines in the file.
static void mergeIntoOneFile(String destinationPathname, List< String > sourcePathnames)
Copies the content of all the files specified in the list of sources and places it into the destinati...
static boolean createDirectory(String fileName)
Creates a directory.
static boolean isLineInTxtFile(String query, File file, boolean add)
Search in a file for a line matching the given string query.
static FileFormat detectKindOfJSONFile(String fileName)
Detect the content of a json file.
static FileFormat detectKindOfSDFFile(String fileName)
Looks into a text file and tries to understand if the file is a collection of parameters for any spec...
static boolean canWriteAndReadTo(String pathName)
Check whether we can write and read to a given pathname.
static void createZipFile(String zipOutputFileName, String[] filesToZip)
Creates a zip file.
static FileFormat detectKindFile(String fileName, FileFormat[] ffs)
Looks into a text file and tries to understand what format it is among the given formats.
static FileFormat detectFileFormat(File inFile)
Inspects a file/folder and tries to detect if there is one of the data sources that is recognized by ...
static void deleteFile(String fileName)
Delete the file.
static String getTempFolder()
Looks for a writable location where to put temporary files and returns an absolute pathname to the fo...
static FileFormat detectKindOfParameterFile(String fileName)
Looks into a text file and tries to understand if the file is a collection of parameters for any spec...
static void addToRecentFiles(File file, FileFormat ff)
Appends an entry to the list of recent files.
static void addToRecentFiles(String fileName, FileFormat ff)
Appends an entry to the list of recent files.
Utility methods for input/output.
static Map< File, FileFormat > readRecentFilesMap()
Reads the file defined in DENOPTIMConstants#RECENTFILESLIST and makes a map that contains the pathnam...
static final String NL
Newline character from system.
static ArrayList< String > readList(String fileName)
Read list of data as text.
static void writeData(String fileName, String data, boolean append)
Write text-like data file.
static final String FS
File separator from system.
Class for de/serializing DENOPTIM graphs from/to JSON format.
Logger class for DENOPTIM.
static final Logger appLogger