简体   繁体   English

Java - 将函数应用于给定目录中的所有文件

[英]Java - Apply Function to All Files in Given Directory

I would like to know if it is possible to apply a function to all files in a directory using Java? 我想知道是否可以使用Java将函数应用于目录中的所有文件?

More specifically, I am looking to read in all images in a folder, convert them to binary (two colours/black and white), and then save the binary image as a new image in another directory (probably directory\\binary , for example). 更具体地说,我希望读取文件夹中的所有图像,将它们转换为二进制(两种颜色/黑白),然后将二进制图像保存为另一个目录中的新图像(例如, directory\\binary ) 。

Something like this: 像这样的东西:

for(all images in folder)
    read in image
    make(binaryImg)
    saveNewImage
endFor

I have 300 images so was hoping that there is a way to do this? 我有300张图片所以希望有办法做到这一点?

Many thanks. 非常感谢。

This should be relatively easy to do, and there are lots of posts here which deal with many of the parts of this program. 这应该相对容易,并且这里有很多帖子涉及该程序的许多部分。 For example, check out these previous questions: 例如,查看以前的这些问题:

Program to get all files within a directory in Java 用Java获取目录中的所有文件的程序

Taking a picture as input, Make grey scale and & then outputting 将图片作为输入,进行灰度等级然后输出

There should be more than enough information there for you to make a start! 那里应该有足够的信息让你开始!

You can do it this way: 你可以这样做:

File dir = new File("/dir/");
for(File f : dir.listFiles())
  processImage(f);

Of course, since you have many files, you can create a Runnable for every file and pass them to an ExecutorService to process in multiple threads: 当然,由于您有许多文件,您可以为每个文件创建一个Runnable ,并将它们传递给ExecutorService以在多个线程中处理:

public static void main(String... args){

    ExecutorService pool = Executors.newFixedThreadPool(4); //nbr of active threads

    File dir = new File("/dir/");
    for(File f : dir.listFiles())
    pool.submit(new Runnable() {
         public void run(){
             processImage(f);
        }
    } 
}

Yes, it's possible. 是的,这是可能的。 Take a look at java.io.File and try searching for topics about working with files in Java for information about how to go about accessing a directory and obtaining a list of the files it contains. 查看java.io.File并尝试搜索有关使用Java中的文件的主题,以获取有关如何访问目录以及获取其包含的文件列表的信息。

If you're looking for somebody to write the code for you, that's unlikely to happen. 如果你正在寻找某人为你编写代码,那不太可能发生。

The only "better way" I can think of is to use a multi threaded design here. 我能想到的唯一“更好的方法”是在这里使用多线程设计。 Every 100 images for example all should be processed in a separate Thread. 例如,所有100个图像都应该在单独的线程中处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM