将多个文件传递给另一个类

时间:2013-06-07 05:29:39

标签: java file dynamic

如何将多个文件传递给另一个类?

我正在开发一个首先压缩图像的应用程序,然后将其转换为pdf。

我写的程序单独运作,即;它压缩图像然后在另一个项目中我使用图像存储的路径将其转换为pdf。

现在我想在同一个项目中同时拥有这两个代码,我遇到的问题是我创建一个循环,我逐个传递路径名。源路径运行良好,但我需要指定目标路径,动态更改名称,我面临的问题。我已附上以下代码,请告诉我该怎么做。

        System.out.println("before convert");
        Conversion cc = new Conversion();
        File directory = new File(Success);
        File[] files = directory.listFiles();
        if(files!=null)
        {
            for(File f:files){
                String path = f.getName();
                System.out.println("The Name of file is="+path); 
                cc.createPdf("path" , "output", true);
                System.out.println("the file is ="+output+".pdf");
                System.out.println("after convert");
            }
        }

在上面的代码中我需要动态更改输出文件名cc.createPdf(“path”,“output”,true);

3 个答案:

答案 0 :(得分:0)

一个简单的实现方法是在将counter文件名附加到output之前保留 int counter = 0; for(File f:files){ String path = f.getName(); System.out.println("The Name of file is="+path); counter++; //increment the counter cc.createPdf("path" , "output"+counter, true); // append it to output System.out.println("the file is ="+output+".pdf"); System.out.println("after convert"); } 外部循环和增量

counter

为了更加健壮,{{1}}可以替换为UUID generator,系统时间(以毫秒为单位等)

答案 1 :(得分:0)

我猜你在使用新创建的.pdf扩展名获取File对象时遇到问题,你必须将其改编为你的代码,但它应该非常简单。

File inputFile = new File("c:\\myimage.png");
String fileName = inputFile.getName();
File pdfFile = new File(inputFile.getParent(), fileName.substring(0, fileName.indexOf(".")) +".pdf");
System.out.println(inputFile + " " + pdfFile);

答案 2 :(得分:0)

我认为你应该通过在名称后添加“.pdf”来保持简单。您正在处理目录的事实可确保源文件名是唯一的。因此,新的“.pdf”名称也是唯一的。

假设您的输出文件位于同一目录中,按名称排序文件也变得更加容易,并立即知道哪些“.pdf”文件与哪些源文件相关。

因此,您的输出文件名只是

String path = f.getName();
String output = path.substring(0, path.lastIndexOf('.')) + ".pdf";
相关问题