I need to display lots of files with filename and icon in my program.
Therefor I am extracting the icons from the files, but it takes too long.
I have tried 2 different methods to extract the icons, but both are really slow (in my case REALLY slow, because I get the files from a networkdrive).
Here is an example, where I extract the icons and count the number of icons (do nothing with the files/icons)
public class Main {
public static void main(String[] args) {
File folder = new File("C:\\Windows\\System32\\");
File[] list = folder.listFiles();
for(int i = 0; i< 3; i++) {
long startTime = System.currentTimeMillis();
System.out.println("Method 1: " + getIconNumber1(list)+ " Icons");
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("Finished Method 1 in " + (float) elapsedTime / 1000 + "sec");
long startTime2 = System.currentTimeMillis();
System.out.println("Method 2: " + getIconNumber2(list)+ " Icons");
long stopTime2 = System.currentTimeMillis();
long elapsedTime2 = stopTime2 - startTime2;
System.out.println("Finished Method 2 in " + (float) elapsedTime2 / 1000 + "sec");
System.out.println("-----------------");
}
}
private static int getIconNumber1(File[] list) {
int nr = 0;
for(File f : list) {
try {
ShellFolder sf = ShellFolder.getShellFolder(f);
ImageIcon icon = new ImageIcon(sf.getIcon(true));
nr++;
} catch (Exception e) {
e.printStackTrace();
}
}
return nr;
}
private static int getIconNumber2(File[] list) {
int nr = 0;
for(File f : list){
FileSystemView view = FileSystemView.getFileSystemView();
Icon icon = view.getSystemIcon(f);
nr++;
}
return nr;
}
}
Is there a faster way to do this?
Related
I am trying to build a plugin on cordova that can find the Bluetooth, USB and Network printer and print text, images, QR code, bar-codes... I have an issue in the network printer scanning, need some help with that. I have this code below that can search for the network printer connected to wifi. It works well with android 7 and 6 but in case of android 5, it is unable to return callback.This probably might be cause of the thread limit or something on android 5
scanWifi(ips, new OnIPScanningCallback() {
#Override
public void onScanningComplete(List<String> results) {
Log.d("TAG", "onScanningComplete: " + results.size()+" : "+results.toString());
Printers printerList =null;
for(String printerIps:results) {
String mac = getHardwareAddress(printerIps);
printerList = new Printers(printerIps, mac);
printers.put(printerIps);
list.add(printerList);
}
Log.d(TAGS,"The List of all wifi Printers : "+list);
}
});
isStart = false;
}
private static void scanWifi(final List<String> ips, final
OnIPScanningCallback callback) {
final Vector<String> results = new Vector<String>();
final int totalSize = ips.size();
final int splitSize = 10;
final int[] index = {0};
final long start = System.currentTimeMillis();
for (int i = 0; i < totalSize; i += splitSize) {
final List<String> child = new ArrayList<String>(ips.subList(i, Math.min(totalSize, i + splitSize)));
new Thread() {
#Override
public void run() {
for (String ip : child) {
Log.d("TAG", " scanning : " + index[0] + ", ip: " + ip);
boolean isPrinter = connect(ip);
if (isPrinter) {
results.add(ip);
}
if (index[0] == ips.size() - 1) {
long end = System.currentTimeMillis();
Log.d("TAG", "scanning time: " + (end - start) / 1000);
callback.onScanningComplete(results);
} else {
index[0]++;
}
}
}
}.start();
}
}
public interface OnIPScanningCallback {
void onScanningComplete(List<String> results);
}
I have also tried the async task and it works on all the versions of android but the problem is the process takes 170 to 193 secs which is way too long as in the above code it was able to do the same in 20 secs
scanWifi(ips, new PrintingPlugin.OnIPScanningCallback() {
#Override
public void onScanningComplete(List<String> results) {
Log.d(TAGS, "onScanningComplete: " + results.size() + " : " + results.toString());
Printers printerList;
for (String printerIps : results) {
String mac = getHardwareAddress(printerIps);
printerList = new Printers(printerIps, mac);
printers.put(printerIps);
list.add(printerList);
}
Log.d(TAGS, "The List of all wifi Printers : " + list);
}
});
isStart = false;
} catch (Exception e) {
Log.e(TAGS, "Error while scanning for wifi"+e.getMessage());
}
return printers;
}
private Integer index = 0;
void resetIndex() {
index = 0;
}
private void scanWifi(final List<String> ips, final PrintingPlugin.OnIPScanningCallback callback) {
Log.d(TAGS, " scanWifi" );
final Vector<String> results = new Vector<String>();
final int totalSize = ips.size();
final int splitSize = 10;
resetIndex();
final long start = System.currentTimeMillis();
for (int i = 0; i < totalSize; i += splitSize) {
final List<String> child = new ArrayList<String>(ips.subList(i, Math.min(totalSize, i + splitSize)));
executeTask(new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
synchronized (index) {
for (String ip : child) {
Log.d(TAGS, " scanning : " + index + ", ip: " + ip);
boolean isPrinter = connect(ip);
if (isPrinter) {
results.add(ip);
}
if (index == ips.size() - 1) {
long end = System.currentTimeMillis();
Log.d(TAGS, "scanning time: " + (end - start) / 1000);
callback.onScanningComplete(results);
} else {
index++;
}
}
}
return null;
}
});
}
public void executeTask(AsyncTask asyncTask) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
asyncTask.execute();
}
}
This is the message that I get when I run on android 5.
D/ConnectivityManager.CallbackHandler: CM callback handler got msg 524290
Any help to make this thing work in any way (the first code to work on android 5 or the second code to work faster and in an efficient way ) will be deeply appreciated. I have looked on the issues related to this but I don't want to use print services.
As the index value was the reason why the callback was not sent, so to solve it just sending the callback as soon as you discover the Network Printer and storing it in a var(JSONArray in my case ) will give you the list of the printers and its effective.
So I'm working on a project for school. I need to record the data from my arrays into Excel and I'm having some trouble. This is part of my experiment class.
public static void exp(Params params) {
Scanner s = new Scanner(System.in);
String temp;
for (temp = ""; temp.isEmpty(); temp = s.nextLine()) {
System.out.println("Enter a directory and filename that you want the results to be saved under.");
System.out.println("(If no directory is specified, results will be in same folder as the jar.)");
}
params.setFileName(temp);
s.close();
System.out.println("Executing...");
long timeArray[] = new long[params.getFinalSize() / params.getIncrement()];
int counter = 0;
SortFacade facade = new SortFacade();
for (int n = params.getInitialSize(); n <= params.getFinalSize(); n += params.getIncrement()) {
System.out.println((new StringBuilder("Array of size: ")).append(n).toString());
long tempTime = 0L;
for (int j = 0; j < params.getNumTrials(); j++) {
System.out.println((new StringBuilder("Trial #")).append(j + 1).toString());
params.generateArrays(n, params.getTypeList());
tempTime += facade.sort(params);
}
timeArray[counter] = tempTime / (long) params.getNumTrials();
counter++;
}
params.setTimeArray(timeArray);
System.out.println("Times for each array size(ms): " + Arrays.toString(timeArray));
System.out.println("Writing to File...");
System.out.println("Complete.");
}
}
Start with Filewriter
Make sure what you write is comma-delimeted and saved as a .csv
Also, take a look at this existing question.
I'm only asking this as a last resort. I'm stumped.
I have written a small app which performs very simple image processing. It is made using JDK 1.8, written in Netbeans 8.0.1 and is running on Debian Linux.
The application captures a large number of individual frames at a certain framerate, set by the user, by calling the 'streamer' webcam program via a process builder. Once it has begun capturing, it begins to translate the frames into RGB values and checks whether or not any pixels are above a user defined threshold. If no pixels exceed this threshold, it simply deletes the frame. If any pixels do exceed it, it moves the frame to a different folder for user inspection. This all works fine. It keeps up with even relatively high framerates and selects appropriate frames as expected. However, when the number of frames processed reaches around 1500 (or fewer for lower framerates), the program is freezing. I've tried issuing the commands to streamer manually at the command line, and it seems perfectly capable of producing as many as required, so I have to assume the issue is with my coding. The images are only small (320x240). Am I somehow maxxing out the available memory (I am getting no errors, just freezing).
The purpose of this program is to detect cosmic ray impacts on a CMOS sensor, part of a friend's dissertation. If I can't get this working reliably, the poor kid's going to have to go through the footage manually!
The code is attached below. Apologies for the length of the code, but as all of it is fairly crucial, I didn't want to omit anything.
package cosmicraysiii;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class CosmicRaysIII {
public static int dark = 0;//Dark current determined by averaging
public static int tol = 0;//Tolerance set by user
public static int frames = 0;//Total number of frames set by user
public static int runs = 0;
public static int rate = 0;//Framerate set by user
public static int time = 0;//Total time calculated
public static String zeros = "";
public static int ready = 0;
public static void main(String[] args) throws IOException, InterruptedException {
//Get directory ID from user
String id = JOptionPane.showInputDialog("Enter a folder name for detections (no ., in name):");
//Get dark current
Dark d = new Dark();
dark = d.getCurrent();
//Get tolerance from user, will be added to dark current.
String t = JOptionPane.showInputDialog("Dark Current = " + dark + "/255\n"
+ "Enter a tolerance (integer values only).\n "
+ "This will be added to the dark current:");
tol = Integer.parseInt(t) + dark;
//Get number of frames from user
String fs = JOptionPane.showInputDialog("Enter the total number of frames required (Mulitples of 500 only):");
frames = Integer.parseInt(fs);
runs = frames / 500;
//Get framerate from user
String r = JOptionPane.showInputDialog("Enter the framerate required:");
rate = Integer.parseInt(r);
//Determine duration
time = (int) Math.round(frames / rate);
//Provide summary for user and request permission to continue
int secs = time % 60;
int mins = (time - secs) / 60;
int hrs = (mins - (mins % 60)) / 60;
if (hrs >= 1) {
mins = mins % 60;
}
String theMessage = "The following parameters have been set:\n"
+ "Tolerance (including dark current): " + tol + "\n"
+ "Frames: " + frames + "\n"
+ "Frame rate: " + rate + " fps\n"
+ "Total capture time: " + time + " sec\n"
+ " " + hrs + " h " + mins + " m " + secs + " s\n"
+ "\n"
+ "Would you like to proceed?";
int result = JOptionPane.showConfirmDialog(null, theMessage, "Continue?", JOptionPane.OK_CANCEL_OPTION);
if (result == 2) {
System.exit(0);
}
//Create directory for data acquisition
ProcessBuilder pb1 = new ProcessBuilder("mkdir", "data");
pb1.start();
//Establish array of filenames
String[] filenames = new String[frames];
//Fill filenames array with filenames
//Taking into consideration that the filename
//will have a varying number of zeros appended
//before the frame number, dependent on the
//order of the frame number
for (int i = 0; i < frames; i++) {
if (i < 10) {
zeros = "00000000";
} else if (i >= 10 && i < 100) {
zeros = "0000000";
} else if (i >= 100 && i < 1000) {
zeros = "000000";
} else if (i >= 1000 && i < 10000) {
zeros = "00000";
} else if (i >= 10000 && i < 100000) {
zeros = "0000";
} else if (i >= 100000 && i < 1000000) {
zeros = "000";
} else if (i >= 1000000 && i < 10000000) {
zeros = "00";
} else if (i >= 10000000 && i < 100000000) {
zeros = "0";
} else {
zeros = "";
}
filenames[i] = "./data/frame" + zeros + i + ".ppm";
}
//Begin data acquisition
new Thread(new Runnable() {
public void run() {
try {
//Capture images
ProcessBuilder pb2 = new ProcessBuilder("streamer", "-t", Integer.toString(frames), "-r", Integer.toString(rate), "-p", "0", "-o", "./data/frame000000000.ppm");
Process p = pb2.start();
p.waitFor();
ready = 1;
} catch (IOException | InterruptedException ex) {
Logger.getLogger(CosmicRaysIII.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
//Sleep to allow some image capture to prevent thread disordering
Thread.sleep(3000);
//Check array size
System.out.println("Array size: " + filenames.length);
//Conduct image analysis
new Thread(new Runnable() {
public void run() {
int done = 0;
int donea = 0;
while (ready == 0) {
for (int i = 0; i < frames; i++) {
File f = new File(filenames[i]);
if (f.exists() && !filenames[i].equals("")) {//Check file still exists
try {
//Perform analysis steps
Analysis a = new Analysis();
//STEP 1: Convert file from P6 to P3
String newfile = a.convert(filenames[i], zeros, i);
//STEP 2: Read file
a.read(newfile, tol, i, id);
filenames[i] = "";
done++;
} catch (IOException ex) {
Logger.getLogger(CosmicRaysIII.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (done > donea) {
System.out.println(done + " files processed");
donea = done;
}
}
}
}
}).start();
}
}
Then the Analyse.java class is as follows:
package cosmicraysiii;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Analysis {
public String convert(String ofile, String zeros, int number) throws IOException {
//Create new file name
String nfile = "./proc/frame" + zeros + number + ".ppm";
//Ensure process directory exists
ProcessBuilder mkdir = new ProcessBuilder("mkdir", "proc");
mkdir.start();
//Convert file to P3 PPM (RGB format) and move to process folder
ProcessBuilder convert = new ProcessBuilder("convert", ofile, "-compress", "none", nfile);
convert.start();
//Delete original file
ProcessBuilder del = new ProcessBuilder("sudo", "rm", ofile);
del.start();
//Return new filename
return nfile;
}
public void read(String filename, int tol, int ix, String id) throws FileNotFoundException, IOException {
int move = 0;
//Make directory for hits
ProcessBuilder mkdir = new ProcessBuilder("mkdir", "hits" + id);
mkdir.start();
//Open reader to read file
File f = new File(filename);
if (f.exists()) {
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
//To eliminate header
int x = 0;
//Iterate through text to find abnormal pixels
while ((line = br.readLine()) != null) {
x++;
String[] pixrgb = line.split("\\ ");
//Iterate through pixels on each line
for (int i = 0; i < pixrgb.length; i++) {
if (x >= 4) {//Eliminate header
//Check each pixel value
try {
int pixval = Integer.parseInt(pixrgb[i]);
if (pixval > tol) {
move = 1;
break;
}
} catch (NumberFormatException ne) {
}
}
}
}
if (move == 1) {
//Move file to hits folder
ProcessBuilder pb3 = new ProcessBuilder("sudo", "cp", filename, "./hits" + id + "/detection" + ix + ".ppm");
pb3.start();
//Delete original file
ProcessBuilder del = new ProcessBuilder("sudo", "rm", filename);
del.start();
}
}
//Delete original file
ProcessBuilder del = new ProcessBuilder("sudo", "rm", filename);
del.start();
}
}
I appreciate this is quite a lengthly chunk of code to be posting. Really appreciate any help that can be given.
G
OK I have managed to solve this by completely overhauling the analysis process. Firstly, rather than converting the image into a P3 .ppm file, I now examine the pixels directly from the image using BufferedReader. Then, I stopped looping through the file list repeatedly. Instead, the loop which calls Analysis() just runs through the list of filenames once. If it encounters a file which does not yet exist, it does Thread.sleep(500) and then tries again. I have now successfully run a batch of 50,000 frames without incident, and there is now much less of a drain on memory thanks to the improved process. Just thought I should place this answer up here in case anyone comes across it. I may post code if anyone wants it.
I am using Ghost4j to convert multipage PDFs to multipage TIFF images. I haven't found an example of how this is done.
Using below code I'm able to convert the multipage PDF to images but how do I create a single multipage TIFF image out of it?
PDFDocument lDocument = new PDFDocument();
lDocument.load(filePath);
// create renderer
SimpleRenderer lRenderer = new SimpleRenderer();
// set resolution (in DPI)
lRenderer.setResolution(300);
// render as images
List<Image> lImages = lRenderer.render(lDocument);
Iterator<Image> lImageIterator = lImages.iterator();
//how to convert the images to a single TIFF image?
While this is not exactly what you are doing I did something similar. I combined multiple images in one directory into a tiff file with separate pages. Take a look at this code and see if you can pick out what you need. Also you will need external jars/libraries for this to work they can be downloaded just google them. I hope this helps you.
public class CombineImages {
private static String directory = null;
private static String combinedImageLocation = null;
private static DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private static int folderCount = 0;
private static int totalFolderCount = 0;
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the directory path that contains the images: ");
directory = scanner.nextLine(); //initialize directory
System.out.println("Please enter a location for the new combined images to be placed: ");
combinedImageLocation = scanner.nextLine(); //initialize directory
if(!(combinedImageLocation.charAt((combinedImageLocation.length() - 1)) == '\\'))
{
combinedImageLocation += "\\";
}
if(!(directory.charAt((directory.length() - 1)) == '\\'))
{
directory += "\\";
}
scanner.close();
//directory = "C:\\Users\\sorensenb\\Desktop\\CombinePhotos\\";
//combinedImageLocation = "C:\\Users\\sorensenb\\Desktop\\NewImages\\";
File filesDirectory;
filesDirectory = new File(directory);
File[] files; //holds files in given directory
if(filesDirectory.exists())
{
files = filesDirectory.listFiles();
totalFolderCount = files.length;
folderCount = 0;
if(files != null && (files.length > 0))
{
System.out.println("Start Combining Files...");
System.out.println("Start Time: " + dateFormat.format(new Date()));
combineImages(files);
System.out.println("Finished Combining Files.");
System.out.println("Finish Time: " + dateFormat.format(new Date()));
}
}
else
{
System.out.println("Directory does not exist!");
System.exit(1);
}
}
public static void combineImages(File[] files)
{
int fileCounter = 1;
ArrayList<String> allFiles = new ArrayList<String>();
String folderBase = "";
String parentFolder = "";
String currentFileName = "";
String previousFileName = "";
File previousFile = null;
int counter = 0;
for(File file:files)
{
if(file.isDirectory())
{
folderCount++;
System.out.println("Folder " + folderCount + " out of " + totalFolderCount + " folders.");
combineImages(file.listFiles());
}
else
{
try {
folderBase = file.getParentFile().getCanonicalPath();
parentFolder = file.getParentFile().getName();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(counter == 0)
{
allFiles.add(file.getName().substring(0, file.getName().indexOf('.')));
}
else
{
currentFileName = file.getName();
previousFileName = previousFile.getName();
currentFileName = currentFileName.substring(0, currentFileName.indexOf('.'));
previousFileName = previousFileName.substring(0, previousFileName.indexOf('.'));
if(!currentFileName.equalsIgnoreCase(previousFileName))
{
allFiles.add(currentFileName);
}
}
}
previousFile = file;
counter++;
}
System.out.println("Total Files to be Combined: " + allFiles.size());
for(String currentFile:allFiles)
{
System.out.println("File " + fileCounter + " out of " + allFiles.size() + " CurrentFile: " + currentFile);
try {
createNewImage(currentFile, files, folderBase, parentFolder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileCounter++;
}
}
***public static void createNewImage(String currentFile, File[] files, String folderBase, String parentFolder) throws IOException
{
//BufferedImage image;
int totalHeight = 0;
int maxWidth = 0;
int currentHeight = 0;
ArrayList<String> allFiles = new ArrayList<String>();
for(File file:files)
{
if((file.getName().substring(0, file.getName().indexOf('.'))).equalsIgnoreCase(currentFile))
{
allFiles.add(file.getName());
}
}
allFiles = sortFiles(allFiles);
BufferedImage image[] = new BufferedImage[allFiles.size()];
SeekableStream ss = null;
PlanarImage op = null;
for (int i = 0; i < allFiles.size(); i++) {
ss = new FileSeekableStream(folderBase + "\\" + allFiles.get(i));
ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", ss, null);
op = new NullOpImage(decoder.decodeAsRenderedImage(0),
null, null, OpImage.OP_IO_BOUND);
image[i] = op.getAsBufferedImage();
}
op.dispose();
ss.close();
/*BufferedImage convertImage;
for(int i = 0; i < image.length; i++)
{
convertImage = new BufferedImage(image[i].getWidth(),image[i].getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics g = convertImage.getGraphics();
g.drawImage(convertImage, 0, 0, null);
g.dispose();
image[i] = convertImage;
}*/
File folderExists = new File(combinedImageLocation);
if(!folderExists.exists())
{
folderExists.mkdirs();
}
TIFFEncodeParam params = new TIFFEncodeParam();
params.setCompression(TIFFEncodeParam.COMPRESSION_GROUP3_1D);
int changeName = 1;
String tempCurrentFile = currentFile;
while((new File(combinedImageLocation + tempCurrentFile + "Combined.tif").exists()))
{
tempCurrentFile = currentFile;
tempCurrentFile += ("(" + changeName + ")");
changeName++;
}
currentFile = tempCurrentFile;
OutputStream out = new FileOutputStream(combinedImageLocation + currentFile + "Combined" + ".tif");
ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
Vector vector = new Vector();
for (int i = 1; i < allFiles.size(); i++) {
vector.add(image[i]);
}
params.setExtraImages(vector.iterator());
encoder.encode(image[0]);
for(int i = 0; i < image.length; i++)
{
image[i].flush();
}
out.close();
System.gc();
/*for(String file:allFiles)
{
image = ImageIO.read(new File(folderBase, file));
int w = image.getWidth();
int h = image.getHeight();
totalHeight += h;
if(w > maxWidth)
{
maxWidth = w;
}
image.flush();
}
BufferedImage combined = new BufferedImage((maxWidth), (totalHeight), BufferedImage.TYPE_BYTE_GRAY);
for(String file:allFiles)
{
Graphics g = combined.getGraphics();
image = ImageIO.read(new File(folderBase, file));
int h = image.getHeight();
g.drawImage(image, 0, currentHeight, null);
currentHeight += h;
image.flush();
g.dispose();
}
File folderExists = new File(combinedImageLocation + parentFolder + "\\");
if(!folderExists.exists())
{
folderExists.mkdirs();
}
ImageIO.write(combined, "TIFF", new File(combinedImageLocation, (parentFolder + "\\" + currentFile + "Combined.tif")));
combined.flush();
System.gc();*/
}***
public static ArrayList<String> sortFiles(ArrayList<String> allFiles)
{
ArrayList<String> sortedFiles = new ArrayList<String>();
ArrayList<String> numbers = new ArrayList<String>();
ArrayList<String> letters = new ArrayList<String>();
for(String currentFile:allFiles)
{
try
{
Integer.parseInt(currentFile.substring((currentFile.indexOf('.') + 1)));
numbers.add(currentFile);
}catch(Exception e)
{
letters.add(currentFile);
}
}
//String[] numbersArray = new String[numbers.size()];
//String[] lettersArray = new String[letters.size()];
for(int i = 0; i < numbers.size(); i++)
{
sortedFiles.add(numbers.get(i));
}
for(int i = 0; i < letters.size(); i++)
{
sortedFiles.add(letters.get(i));
}
return sortedFiles;
}
}
Thank you in advance for your help. I am developing a java based tool that is preforming some database work. I have a very simple problem. For some reason the time reported to complete the task is incorrect.
public static void makeDatabaseThreaded() throws IOException, InterruptedException {
final long startTime = System.nanoTime();
ArrayList<String> tablesMade = new ArrayList<>();
File rootDirectory = root;
String[] files = rootDirectory.list();
double percentDone = 0;
double numOfTablesMade = 0;
double numberOfTables = 62.0;
DatabaseBuilderThread lastThread = null;
for (int i = 0; i <= files.length - 1; i++) {
if (!files[i].contains(".csv")) {
continue;
}
File file = new File(rootDirectory + File.separator + files[i]);
String tableName = getTableNameFromFile(file);
if (!tablesMade.contains(tableName)) {
tablesMade.add(tableName);
DatabaseBuilderThread thread = new DatabaseBuilderThread(i, file);
lastThread = thread;
thread.start();
threadsRunning++;
numOfTablesMade++;
percentDone = (int) (100.0 * (numOfTablesMade) / (numberOfTables));
while (threadsRunning > 10) {
Thread.sleep(1000);
}
System.out.println(percentDone + "% done. Making Table For File: " + file.getName());
}
}
//Make Sure all threads are done
lastThread.join();
final long endTime = System.nanoTime();
final long duration = endTime - startTime;
Time time = new Time(duration);
System.out.println("Done Making The Database. It took " + time.toString());
}
The program reports that it worked about twice as long at it truly did for the cases that I ran.
Thanks
System.nanoTime() returns time values in nanoseconds. Time() takes a value in milliseconds as a parameter. This would throw your time value off by a factor of 10^-6.
Time takes milliseconds as a constructor parameter, where as nanoTime() gives you nanoseconds precision, could that be the problem?
discussion here: System.currentTimeMillis vs System.nanoTime