Can do something like this:
public static void convertAllCSV(String directory)
{
try
{
ArrayList<String> files = findFiles(directory); //Returns list of all files in folder with .pdf extension
for (String s : files)
{
convertSingleCSV(s, directory); //Your current code placed into a method
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
With the findFiles
method looking like this:
public static ArrayList<String> findFiles(String directory) throws IOException
{
ArrayList<String> fileList = new ArrayList<String>();
File dir = new File(directory);
String ext = ".pdf";
String[] files = dir.list();
for (String file : files)
{
//If the file ends with .pdf
if(file.endsWith(ext))
{
fileList.add(file);
}
}
return fileList;
}
There are basically 2 steps you need to add. You need to pass a directory name and find all the files in the directory with the extension .pdf
and then use it to call your original method one at a time through a loop.
convertSingleCSV
is your code placed into a method then uses the filename and directory to output the new file. So instead of hard coding name of the FileOutputStream
just convert it by doing something like this:
String fileNameNoExtension = fileName.substring(0, fileName.lastIndexOf('.')); //Cuts off the file extension to append csv instead of pdf
FileOutputStream fos = new FileOutputStream(directory + "\\" + fileNameNoExtension + ".csv")
The advantage of doing it this way is you keep the original file names but just create a new file with the .csv
extension, and it will only attempt to convert any .pdf
files and you do not have to worry about ensuring other files are not in the directory passed.