I'm taking HTML file and one XSLT file as input and generating HTML output but in my folder there are multiple HTML files and I've to take each of them as input and generate the corresponding output file while XSLT input file remains same every time. Currently in my code I'm repeating the code block every time to take the input HTML file. Instead of this I want to iterate over all the HTML files in the folder and take them as input file one by one to generate the output. In my current code file names are also fixed like part_1.html but it can vary and in that case this code won't work and this will create problem. Can anyone please help out in this matter:
Thanking you!
Current Java code (Sample for two files):
public void tranformation() {
// TODO Auto-generated method stub
transform1();
transform2();
}
public static void transform1(){
String inXML = "C:/SCORM_CP/part_1.html";
String inXSL = "C:/source/xslt/html_new.xsl";
String outTXT = "C:/SCORM_CP/part1_copy_copy.html";
String renamedFile = "C:/SCORM_CP/part_1.html";
File oldfile =new File(outTXT);
File newfile =new File(renamedFile);
HTML_Convert hc = new HTML_Convert();
try {
hc.transform(inXML,inXSL,outTXT);
} catch(TransformerConfigurationException e) {
System.err.println("Invalid factory configuration");
System.err.println(e);
} catch(TransformerException e) {
System.err.println("Error during transformation");
System.err.println(e);
}
try{
File file = new File(inXML);
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
public static void transform2(){
String inXML = "C:/SCORM_CP/part_2.html";
String inXSL = "C:/source/xslt/html_new.xsl";
String outTXT = "C:/SCORM_CP/part2_copy_copy.html";
String renamedFile = "C:/SCORM_CP/part_2.html";
File oldfile =new File(outTXT);
File newfile =new File(renamedFile);
HTML_Convert hc = new HTML_Convert();
try {
hc.transform(inXML,inXSL,outTXT);
} catch(TransformerConfigurationException e) {
System.err.println("Invalid factory configuration");
System.err.println(e);
} catch(TransformerException e) {
System.err.println("Error during transformation");
System.err.println(e);
}
try{
File file = new File(inXML);
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
public void transform(String inXML,String inXSL,String outTXT)
throws TransformerConfigurationException,
TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xslStream = new StreamSource(inXSL);
Transformer transformer = factory.newTransformer(xslStream);
transformer.setErrorListener(new MyErrorListener());
StreamSource in = new StreamSource(inXML);
StreamResult out = new StreamResult(outTXT);
transformer.transform(in,out);
System.out.println("The generated XML file is:" + outTXT);
}
}
File dir = new File("/path/to/dir");
File[] htmlFiles = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith(".html");
}
});
if (htmlFiles != null) for (File html: htmlFiles) {
...
}
You have to implement something like
public class Transformation {
public static void main (String[] args){
transformation(".", ".");
}
public static void transform(String inXML, String inXSL, String outTXT, String renamedFile){
System.out.println(inXML);
System.out.println(inXSL);
System.out.println(outTXT);
System.out.println(renamedFile);
}
public static void transformation(String inFolder, String outFolder){
File infolder = new File(inFolder);
File outfolder = new File(outFolder);
if (infolder.isDirectory() && outfolder.isDirectory()){
System.out.println("In " + infolder.getAbsolutePath());
System.out.println("Out " + outfolder.getAbsolutePath());
File[] listOfFiles = infolder.listFiles();
String outPath = outfolder.getAbsolutePath();
String inPath = infolder.getAbsolutePath();
for (File f: listOfFiles) {
if (f.isFile() ) {
System.out.println("File " + f.getName());
int indDot = f.getName().lastIndexOf(".");
String name = f.getName().substring(0, indDot);
String ext = f.getName().substring(indDot+1);
if (ext != null && ext.equals("html")){
transform(f.getAbsolutePath(), inPath+File.separator+name+".xsl", outPath+File.separator+name+".txt", outPath+File.separator+name+".html");
}
}
}
}
}
}
First you should write a method that take inXML, inXSL, outTXT and renamedFile as arguments.
Then, using the list() method of the File class, that eventually take a FilenameFilter, you may iterate over the files you want to transform.
Here is a sample of FilenameFilter :
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.contains("part");
}
};
Regards
use DirectoryScanner which will make your job easier
Example of usage:
String[] includes = {"**\*.html"};
ds.setIncludes(includes);
ds.setBasedir(new File("test"));
ds.setCaseSensitive(true);
ds.scan();
System.out.println("FILES:");
String[] files = ds.getIncludedFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
http://plexus.codehaus.org/plexus-utils/apidocs/org/codehaus/plexus/util/DirectoryScanner.html
Related
I have made the code which renames all the jpg files in a directory from 1 to n (number of files)..
if there were let say 50 jpg files that after running the program all the files are renamed to 1.jpg ,2.jpg and so on till 50.jpg
But i am facing the problem if I manually rename the file let say 50.jpg to aaa.jpg then again running the program doesn't rename that file
I have wasted one day to resove that issue
Kindly help me
Code:
public class Renaming {
private static String path; // string for storing the path
public static void main(String[] args) {
FileReader fileReader = null; // filereader for opening the file
BufferedReader bufferedReader = null; // buffered reader for buffering the data of file
try{
fileReader = new FileReader("input.txt"); // making the filereader object and paasing the file name
bufferedReader = new BufferedReader(fileReader); //making the buffered Reader object
path=bufferedReader.readLine();
fileReader.close();
bufferedReader.close();
}
catch (FileNotFoundException e) { // Exception when file is not found
e.printStackTrace();
}
catch (IOException e) { // IOException
e.printStackTrace();
}
finally {
File directory=new File(path);
File[] files= directory.listFiles(); // Storing the all the files in Array
int file_counter=1;
for(int file_no=0;file_no<files.length;file_no++){
String Extension=getFileExtension(files[file_no]); //getting the filw extension
if (files[file_no].isFile() && (Extension .equals("jpg")|| Extension.equals("JPG"))){ // checking that if file is of jpg type then apply renaming // checking thaat if it is file
File new_file = new File(path+"\\"+files[file_no].getName()); //making the new file
new_file.renameTo(new File(path+"\\"+String.valueOf(file_no+1)+".jpg")); //Renaming the file
System.out.println(new_file.toString());
file_counter++; // incrementing the file counter
}
}
}
}
private static String getFileExtension(File file) { //utility function for getting the file extension
String name = file.getName();
try {
return name.substring(name.lastIndexOf(".") + 1); // gettingf the extension name after .
} catch (Exception e) {
return "";
}
}`
first of all, you should use the path separator / . It's work on Windows, Linux and Mac OS.
This is my version of your problem to rename all files into a folder provide. Hope this will help you. I use last JDK version to speed up and reduce the code.
public class App {
private String path = null;
public static int index = 1;
public App(String path){
if (Files.isDirectory(Paths.get( path ))) {
this.path = path;
}
}
public void rename() throws IOException{
if ( this.path != null){
Files.list(Paths.get( this.path ))
.forEach( f ->
{
String fileName = f.getFileName().toString();
String extension = fileName.replaceAll("^.*\\.([^.]+)$", "$1");
try {
Files.move( f ,Paths.get( this.path + "/" + App.index + "." + extension));
App.index++;
} catch (IOException e) {
e.printStackTrace();
}
}
);
}
}
public static void main(String[] args) throws IOException {
App app = new App("c:/Temp/");
app.rename();
}
}
I am developing an Android application that produces results and I am saving this results in a CSV file. After that I want to close the app, open it again, get other results and write them at the end of the same existing CSV file. Right now every time it ovverrides the previous results.
This is my class to save the results in a CSV file:
public class SaveCSV {
private File file;
private RandomAccessFile randomAccessFile;
public SaveCSV(){
this.file = getPath("RisultatiTest.csv");
try {
this.randomAccessFile = new RandomAccessFile(file, "rwd");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void salvaRisultati (int[] array) {
try {
file.createNewFile();
String s = "";
for (int i = 0; i < array.length; i++) {
s = s + array[i] + ",";
}
randomAccessFile.writeBytes(s);
randomAccessFile.writeBytes("\n");
} catch (IOException e) {
throw new RuntimeException("Unable to create File " + e);
}
}
public static File getPath(String fileName){
return new File(Environment.getExternalStorageDirectory(), fileName);
}
}
i want to populate Folder Name With Sub Folder name on KendoDrop Down . so i want to Convert Folder Directory in JSOn Format How can i Do That ?
public class FolderPath {
public static void main(String[] args) throws IOException {
File currentDir = new File("Folder URL "); // current directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
StringBuilder sb1 = new StringBuilder("[");
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
sb1 = sb1.append("{\"JSONKEY\":\"" + file.getCanonicalPath() + "\"},");
String str = file.getCanonicalPath();
displayDirectoryContents(file);
} else {
}
}
sb1.deleteCharAt(sb1.length() - 1);
sb1 = sb1.append("]");
System.out.println("s2==>" + sb1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here i am Not Getting Full Directroy into JSOn Please Help
You are creating a StringBuilder object on each iteration. That's why your concatenation does not work.
Consider the contents of you C:\test is composed of 3 directories:
c:\test
|
+--css
| +--less
+--js
The code below, returns:
[{"JSONKEY":"C:\test\css"},
{"JSONKEY":"C:\test\css\less"},
{"JSONKEY":"C:\test\js"}]
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
public class FolderPath {
private static FileFilter onlyDirectories = new FileFilter() {
#Override
public boolean accept(File file) {
return file.isDirectory();
}
};
public static void main(String[] args) {
File currentDir = new File("C:\\test"); // current directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
StringBuilder sb1 = new StringBuilder("[");
doDisplayDirectoryContents(dir, sb1);
if (sb1.length() > 1) {
sb1.deleteCharAt(sb1.length() - 1);
}
sb1.append("]");
System.out.println(sb1);
}
private static void doDisplayDirectoryContents(File dir, StringBuilder sb1) {
File[] files = dir.listFiles(onlyDirectories);
if (files != null) {
for (File file : files) {
try {
sb1.append("{\"JSONKEY\":\"" + file.getCanonicalPath() + "\"},");
doDisplayDirectoryContents(file, sb1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public List<Object> getDirectoryContents(String path) throws IOException {
File directory = new File(path);
File[] files;
enter code here FileFilter fileFilter = file -> file.isDirectory() || file.isFile();
files = directory.listFiles(fileFilter);
List<Object> directoryContent = new ArrayList<>();
if(files != null) {
for (int i = 0; i < files.length; i++) {
File filename = files[i];
String folderPath[] =filename.toString().split("/");
if(files[i].isDirectory()) {
Folder folder = new Folder();
folder.setName(folderPath[folderPath.length - 1]);
folder.setType("folder");
folder.setChildren(mapper.readTree(mapper.writeValueAsString(getDirectoryContents(path + "/" + folder.getName()))));
directoryContent.add(folder);
}
else{
Files file = new Files();
file.setName(folderPath[folderPath.length - 1]);
file.setType("file");
directoryContent.add(file);
}
}
}
return directoryContent;
}
public class Files {
private String name;
private String type = "file";
}
public class Folder {
private String name;
private String type = "folder";
private JsonNode children;
}
I am trying to zip multiple folders using Java. Below is my code.
if (CompressType.ZIP == zip){
File f = null;
for (File serlectFile : serlectFiles){
f = new File(serlectFile.getAbsolutePath());
filePath = f;
System.out.println("NIO Folders 1122 : " + filePath);
new Thread(new Runnable(){
public void run(){
try{
compressFolder.createZip(filePath.getPath(), destination.getPath());
JOptionPane.showMessageDialog(null, " Backup Created .....", "Alert", 1);
dispose();
} catch (IOException ex){
JOptionPane.showMessageDialog(null, "Error ! ");
ex.printStackTrace();
}
}
}).start();
}
}
This is the code I've tried to do above task . But unfortunately I couldn't complete it . Because when I send 'filepath.getPath()' to 'createZip()' method it is got just only one directory at the time . But when I was printed filepath before the method calling it gave me following . ''NIO Folders 1122 : C:\Users\user\Desktop\backup ''-
'' NIO Folders 1122 : C:\Users\user\Desktop\contact''.
The reason I can think is, the applicartion is running without waiting for one thread to complete. Therefore all the threads are running in a loop. Below is my zipping code, which runs inside the above mentioned thread.
public void createZip(String directoryPath, String zipPath) throws IOException{
value = countFilesInDirectory(new File(directoryPath));
ExpressWizard.backupProgressBar.setMaximum(value);
FileOutputStream fOut = null;
BufferedOutputStream bOut = null;
ZipArchiveOutputStream tOut = null;
try{
fOut = new FileOutputStream(new File(zipPath));
bOut = new BufferedOutputStream(fOut);
tOut = new ZipArchiveOutputStream(bOut);
addFileToZip(tOut, directoryPath, "");
} finally {
tOut.finish();
tOut.close();
bOut.close();
fOut.close();
}
}
#SuppressWarnings("empty-statement")
private void addFileToZip(ZipArchiveOutputStream zOut, String path, String base) throws IOException{
File f = new File(path);
String entryName = base + f.getName();
ZipArchiveEntry zipEntry = new ZipArchiveEntry(f, entryName);
zOut.putArchiveEntry(zipEntry);
if (f.isFile()) {
FileInputStream fInputStream = null;
try{
fInputStream = new FileInputStream(f);
IOUtils.copy(fInputStream, zOut);
zOut.closeArchiveEntry();
} finally {
IOUtils.closeQuietly(fInputStream);
}
System.out.println(f.getAbsolutePath());
counter++;
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
ExpressWizard.backupProgressBar.setValue(counter);
ExpressWizard.filesTextArea.append(f.getAbsolutePath() + "\n");
}
});
if (ExpressWizard.backupProgressBar.getValue() == counter){
ExpressWizard.backUpButton.setEnabled(false);
}
} else{
zOut.closeArchiveEntry();
File[] children = f.listFiles();
if (children != null){
for (File child : children){
addFileToZip(zOut, child.getAbsolutePath(), entryName + "/");
System.out.println("File: " + child.getAbsolutePath());
}
}
}
}
How can I execute this code, one by one? In other words, the zip file thread should run for one folder; the loop should wait; when the zip is completes, the second folder starts zipping; The loop waits for the end of thread; then the third folder and so on.
Any ideas?
After writing the text files into a directory, i am trying to delete the empty files written by the PrintWriter.
File.delete() function fails to delete the file. Below is the code for writing and deleting.
private static void writeFile(ArrayList<ArrayList<String>> listRowVal, String szOutputDir, ArrayList<String> listHeader){
PrintWriter pw = null;
try {
ArrayList<String> listCells = listRowVal.get(0);
int iCells = listCells.size();
for(int k=0; k<iCells; k++){
String language = listHeader.get(k);
String szFileName = "files_"+ language +".csv";
pw = new PrintWriter(new FileWriter(szOutputDir + File.separator + szFileName));
for(ArrayList<String> listNCRCellVal : listRowVal){
String szVal = listNCRCellVal.get(k);
if(szVal != null && szVal.trim().length() > 0){
pw.println(szVal);
}
pw.flush();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(pw != null){
pw.close();
pw = null;
}
//System.gc();
deleteEmptyFiles(szOutputDir);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static void deleteEmptyFiles(String szDirPath) {
File file = new File(szDirPath);
if (file.isDirectory()) {
String[] files = file.list();
if (files.length > 0) {
for (String szFileName : files) {
File deleteFile = new File(szDirPath + File.separator + szFileName);
if (deleteFile.length() == 0) {
//deleteFile.setWritable(true, false);
boolean bdeleted = deleteFile.delete();
if(bdeleted){
System.out.println(deleteFile.getName() + " deleted.");
}
}
}
}
}
}
What is going wrong..??
You must close each PrintWriter, i.e. pw.close() must be on the end of "k" loop.