I'm very new to Java and I'm recently making a program which reads image files(jpg) from one directory, and write(copy) them to another directory.
I can't use imageio or move/copy methods and I also have to check the time consuming caused by the R/W operation.
The problem is I wrote some codes below and it runs, but all of my output image files in the destination have 0 byte and have no contents at all. I can see only black screens which have no bytes when I open the result images.
public class image_io {
public static void main(String[] args)
{
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
// getting path
File directory = new File("C:\\src");
File[] fList = directory.listFiles();
String fileName, filePath, destPath;
// date for time check
Date d = new Date();
int byt = 0;
long start_t, end_t;
for (File file : fList)
{
// making paths of source and destination
fileName = file.getName();
filePath = "C:\\src\\" + fileName;
destPath = "C:\\dest\\" + fileName;
// read the images and check reading time consuming
try
{
fis = new FileInputStream(filePath);
bis = new BufferedInputStream(fis);
do
{
start_t = d.getTime();
}
while ((byt = bis.read()) != -1);
end_t = d.getTime();
System.out.println(end_t - start_t);
} catch (Exception e) {e.printStackTrace();}
// write the images and check writing time consuming
try
{
fos = new FileOutputStream(destPath);
bos = new BufferedOutputStream(fos);
int idx = byt;
start_t = d.getTime();
for (; idx == 0; idx--)
{
bos.write(byt);
}
end_t = d.getTime();
System.out.println(end_t - start_t);
} catch (Exception e) {e.printStackTrace();}
}
}
}
Is FileInput/OutputStream doesn't support image files? Or is there some mistakes in my code?
Please, somebody help me..
There are multiple problems with your code:
With this loop
you are trying to read the file. The problem with it is, that you always only remember a single byte and store it to
byt
. In the next iteration it gets overridden by the next byte in the file until you reach the end, in which case the read value is-1
. So the net effect of this loop isbyt
being equal to-1
. You need to read all bytes to some buffer, e.g. an array that is large enough to hold the whole file.Another problem here is that you repeatedly set
start_t
. You probably want to do this only once before entering the loop. Note also thatd.getTime()
will always return the same value, the one it got when you didDate d = new Date();
. You probably want to callSystem.currentTimeMillis()
or something like that instead.After you have fixed the issues above, you need to adjust the write loop accordingly.
You should also look into some Java coding guideline, as your code violates several common practices:
image_io
=>ImageIO
,start_t
=>startTime
…)idx
)When you have your program doing what you want you could post it on Code Review to get additional advices on what you could improve.