2016-02-09 39 views
-3

我对Java很陌生,最近我正在制作一个程序,它从一个目录读取图像文件(jpg),并将它们写入(复制)到另一个目录。用Java在本地文件系统之间无imageio读写图像

我无法使用imageio或移动/复制方法,而且我还必须检查由R/W操作导致的耗时。

问题是我在下面写了一些代码,它运行,但目标中的所有输出图像文件都有0字节,根本没有内容。 当我打开结果图像时,我只能看到没有字节的黑色屏幕。

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();} 
    } 
} 

}

是的FileInput/OutputStream中不支持的图像文件? 或者在我的代码中有一些错误?

请,有人帮助我..

+0

您可能想检查一下,即使您可能不会使用Apache方法(我认为第一种方法最适合您的需要):http://examples.javacodegeeks。COM /核心的Java/IO /文件/ 4路到复制文件中的Java / – T145

回答

0

有多个问题与您的代码:

有了这个循环

do 
{ 
    start_t = d.getTime(); 
} 
while ((byt = bis.read()) != -1); 

你试图读取该文件。问题在于,你总是只记住一个字节并将其存储到byt。在下一次迭代中,它会被文件中的下一个字节覆盖,直到达到结尾,在这种情况下,读取值为-1。所以这个循环的净效果是byt等于-1。您需要将所有字节读取到某个缓冲区,例如一个足够容纳整个文件的数组。

此处的另一个问题是您重复设置start_t。进入循环之前,您可能只需要执行一次此操作。还要注意,d.getTime()将始终返回相同的值,即您在执行Date d = new Date();时得到的值。你可能想打电话System.currentTimeMillis()或类似的东西。

解决了上述问题后,需要相应地调整写入循环。

你也应该考虑一些Java编码指南,为你的代码侵犯了几种常见的做法:类和变量

  • 命名风格(image_io =>ImageIOstart_t =>startTime ...)
  • 宣言(例如您的流和idx
  • 某些缩进问题(例如,第一次尝试的块没有缩进)
  • 你不关闭你的流。如果你有Java 7+可用,你应该看看try-with-resources,它会自动关闭你的流。

当你的程序做你想做的事情时,你可以在Code Review上发布它,以获得关于你可以改进的东西的额外建议。

相关问题