java

move directory in Java ,convert file to linux,remove CRLF

privatevoid moveFilesFromSourceToDestination(String sourceFolder,String destinationFolder) throws IOException{log.info( “trying move “+sourceFolder+” to “+destinationFolder );

File sFolder = new File(sourceFolder);

File dFolder = new File(destinationFolder);

for (File file : sFolder.listFiles()){

if (file.isFile()){

File newFile = new File(dFolder.getAbsolutePath() + “/”+file.getName());

moveFile(file,newFile);

}elseif (file.isDirectory()){

File newFile = new File(dFolder.getAbsolutePath() + “/”+file.getName());

newFile.mkdir();

moveFilesFromSourceToDestination(file.getAbsolutePath(),newFile.getAbsolutePath());

File oldFile = new File(sFolder.getAbsolutePath() + “/”+file.getName());

oldFile.delete();

}

}

log.info( “move “+sourceFolder+” to “+destinationFolder+” Done succesfully “ );

}

privatevoid moveFile(File file, File newFile) throws IOException {

FileReader in = new FileReader(file);

FileWriter out = new FileWriter(newFile);

int c;

while ((c = in.read()) != -1)

out.write(c);

in.close();

out.close();

//delete old one and convert the new one from dos2linux

file.delete();

convertFromDosToLinux(newFile.getName(),newFile.getParentFile().getAbsolutePath());

}

privatevoid convertFromDosToLinux(String fileName,String folderName) throws IOException{

//create shell script

FileWriter fstream = new FileWriter(folderName+“/script.sh”);

BufferedWriter out = new BufferedWriter(fstream);

out.write(“tr -d ‘\\r’ “+“<“+folderName+“/”+fileName+“> “+folderName+“/temp”);

out.close();

runShellScript(folderName+“/script.sh”);

//delete script and input file and rename the output

File fileTobeDeleted = new File(folderName+“/”+fileName);

fileTobeDeleted.delete();

File fileTobeRenamed = new File(folderName+“/temp”);

fileTobeRenamed.renameTo(fileTobeDeleted);

File scriptToBeDeleted = new File(folderName+“/script.sh”);

scriptToBeDeleted.delete();

}

privatevoid runShellScript(String shellScript) throws IOException {

Runtime run=Runtime.getRuntime();

String command = “sh “+shellScript;

Process process=run.exec(command);

InputStream stderr = process.getErrorStream();

InputStreamReader isr = new InputStreamReader(stderr);

BufferedReader br = new BufferedReader(isr);

String line = null;

System.out.println(“start converting …..”);

while ( (line = br.readLine()) != null)

System.out.println(line);

int exitVal;

try {

exitVal = process.waitFor();

if (exitVal == 0){

System.out.println(“—converting done—- “ );

log.info(“—converting done —- “);

}

else{

System.out.println(“—converting failure—- “ );

log.info(“—converting failure —- “);

}

} catch (InterruptedException e) {

e.printStackTrace();

}

}

Advertisements