How do I copy the folders inside the nested folders at loadonstartup? - java

I have around 150 folder and inside each folder images are present , I am trying to copy the whole directory inside the other directory . For few directories it is working then after it stops automatically without throwing any error or exception . I am using FileUtils method to achieve this .
org.apache.commons.io.FileUtils.copyDirectoryToDirectory(originalImageFolder, new File(this.ctx.getRealPath(newFilePath)));

I provided an alternate solution without the need to use a third party, such as apache FileUtils. This can be done through the command line.
I tested this out on Windows and it works for me. A Linux solution follows.
Here I am utilizing Windows xcopy command to copy all files including subdirectories.
The parameters that I pass are defined as per below.
/e - Copies all subdirectories, even if they are empty.
/i - If Source is a directory or contains wildcards and Destination
does not exist, xcopy assumes Destination specifies a directory name
and creates a new directory. Then, xcopy copies all specified files
into the new directory.
/h - Copies files with hidden and system file attributes. By default,
xcopy does not copy hidden or system files
My example(s) utilizes the ProcessBuilder class to construct a process to execute the copy(xcopy & cp) commands.
Windows:
String src = "C:\\srcDir";
String dest = "C:\\destDir";
List<String> cmd = Arrays.asList("xcopy", src, dest, "/e", "/i", "/h");
try {
Process proc = new ProcessBuilder(cmd).start();
BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = inp.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Linux:
String src = "srcDir/";
String dest = "~/destDir/";
List<String> cmd = Arrays.asList("/bin/bash", "-c", "cp", "r", src, dest);
try {
Process proc = new ProcessBuilder(cmd).start();
BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = inp.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
A combo that can work on both Windows or Linux environments.
private static final String OS = System.getProperty("os.name");
private static String src = null;
private static String dest = null;
private static List<String> cmd = null;
public static void main(String[] args) {
if (OS.toLowerCase().contains("windows")) { // setup WINDOWS environment
src = "C:\\srcDir";
dest = "C:\\destDir";
cmd = Arrays.asList("xcopy", src, dest, "/s", "/e", "/i", "/h");
System.out.println("on: " + OS);
} else if (OS.toLowerCase().contains("linux")){ // setup LINUX environment
src = "srcDir/";
dest = "~/destDir/";
cmd = Arrays.asList("/bin/bash", "-c", "cp", "r", src, dest);
System.out.println("on: " + OS);
}
try {
Process proc = new ProcessBuilder(cmd).start();
BufferedReader inp = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = inp.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}

Related

The system cannot find the file specified - Netbeans Maven Project

I need to read two .json files, I have added them to my src folder of NetBeans folder but it is not finding the file.
I have tried using path in following ways,
"/krf_input_cases.json",
"krf_input_cases.json",
"/com.mycompany.reasoner/krf_input_cases.json"
after checking here on StackOverflow but it is not working. The still same error that file cannot be found!
Here you can see where is my file is in the document tree:
This is where I have specified my file paths
//file paths
private static final String KRF_INPUT_CASES = "krf_input_cases.json";
private static final String KRF_KNOWLEDGE_BASE = "krf_knowledge_base.json";
Here is the function reading the file which is throwing an exception!
public static String loadData(String filePath) throws Exception {
System.out.println("line");
BufferedReader br = null;
try{br = new BufferedReader(new FileReader(
new File(filePath)));} catch (Exception e){
System.out.println(e.getMessage());
}
System.out.println("line1");
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line.trim());
}
br.close();
return sb.toString();
}

Executing python script from within JAR file

I am trying to write a Java application that executes a python script in order to return a value to the original program. However, the script is written in Python3 so I can't use Jython.
My current program works fine in Intellij but when I export to a JAR file it no longer works (I'm assuming because the filepath is different). I know questions similar to this have been asked in the past but none of the solutions seem to be working.
String currentPath = new File("").getAbsolutePath();
String path = Paths.get(currentPath, "src", "com", "engine", "pythonScript.py").toUri().toString();
String[] cmd = new String[]{"python", path, data};
try {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String output;
while ((output = stdInput.readLine()) != null) {
System.out.println(output);
if (checkOutput(output)) {
return output;
}
}
BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String s;
while ((s=error.readLine()) != null) {
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}

How can I get the rt.exec to run the command line in a different folder instead of the root folder

I would like to create a folder call pythoncode within my root directory and have rt.exec * run within this folder so my *.py files can be in a seperate folder.
My test code
void test()
{
Runtime rt;
rt = Runtime.getRuntime();
String line = null;
try{
Process pr = rt.exec("python chart.py");
InputStreamReader mInputStreamReader = new InputStreamReader( pr.getInputStream());
BufferedReader input = new BufferedReader( mInputStreamReader );
while ( (line = input.readLine()) != null)
System.out.println(line);
}
catch( Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage(), "Abort", JOptionPane.INFORMATION_MESSAGE);
}
} // end methed

sed command not working from java

I am trying to run a sed command from java without success. Here is my java code:
String[] cmd = {"sed", "-i", "'"+lineIndex+"s/"+line+"/"+currentBid+"/g'", "/data/jsp/items.xml"};
Runtime.getRuntime().exec(cmd);
I also tried:
String[] cmd = {"/bin/sh","-c","sed", "-i", "'"+lineIndex+"s/"+line+"/"+currentBid+"/g'", "/data/jsp/items.xml"};
Runtime.getRuntime().exec(cmd);
Thing is, if I print out the contents of the cmd String and run it in a terminal it does work. It's just not executing it from java for some reason. Te make this more clear, when I run the command directly from a terminal the file "items.xml" changes. When I run it from java the file does not change. I've verified that the command is correct as sown below.
Am I missing something?
The output from cmd is sed -i '21s/2/102/g' /data/jsp/items.xml
** EDIT
I made the following changes based on comments below. No change in output however.
String[] cmd = {"/bin/sh","-c","sed", "-i", "'"+lineIndex+"s/"+line+"/"+currentBid+"/g'", "/data/jsp/items.xml"};
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line2 = reader.readLine();
while (line2 != null) {
line2 = reader.readLine();
}
reader.close();
Try that :)
The advantage of this solution , it's more easier to debugging because you have the temporary file !
String lineIndex="21";
String line="2";
String currentBid="102";
File temp = File.createTempFile("temp-sh", ".sh");
FileWriter fw = new FileWriter(temp);
fw.write("#!/bin/bash\n");
fw.write("sed -i '"+lineIndex+"s/"+line+"/"+currentBid+"/g' data/jsp/items.xml\n");
fw.close();
System.out.println(". "+temp.getAbsolutePath());
Runtime.getRuntime().exec(". "+temp.getAbsolutePath());
You should probably use a ProcessBuilder instead of Runtime.exec, perhaps something like this -
try {
String replaceCommand ="'"+lineIndex+"s/"+line+"/"+currentBid+"/g'";
String [] cmd = new String[] {
"sed", "-i", replaceCommand, "/data/jsp/items.xml"
};
Process process = new ProcessBuilder(cmd)
.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String lineRead;
System.out.printf("Output of running %s is:",
Arrays.toString(cmd));
while ((lineRead = br.readLine()) != null) {
System.out.println(lineRead);
}
} catch (IOException e) {
e.printStackTrace();
}
You need to make sure the path to the file is correct, java may not have the same path to the file unless it is in the jar. You can do this by trying to open the file or checking if it exists before passing it to the command.
see: How to read file from relative path in Java project? java.io.File cannot find the path specified
Honestly there is no need to externally execute sed in this case. Read the file in Java and use Pattern. Then you have code that could run on any platform. Combine this with org.apache.commons.io.FileUtils and you can do it in a few lines of code.
final File = new File("/data/jsp/items.xml");
String contents = FileUtils.readFileToString(file, StandardCharsets.UTF_8.name());
contents = Pattern.compile(line).matcher(contents).replaceAll(currentBid);
FileUtils.write(file, contents);
Or, in a short, self-contained, correct example
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
public final class SedUtil {
public static void main(String... args) throws Exception {
final File file = new File("items.xml");
final String line = "<bid>\\d+</bid>";
final String currentBid = "<bid>20</bid>";
final String data = "<bids><bid>10</bid></bids>";
FileUtils.write(file, data);
sed(file, Pattern.compile(line), currentBid);
System.out.println(data);
System.out.println(FileUtils.readFileToString(file, StandardCharsets.UTF_8));
}
public static void sed(File file, Pattern regex, String value) throws IOException {
String contents = FileUtils.readFileToString(file, StandardCharsets.UTF_8.name());
contents = regex.matcher(contents).replaceAll(value);
FileUtils.write(file, contents);
}
}
which gives output
<bids><bid>10</bid></bids>
<bids><bid>20</bid></bids>

Storing the o/p of Runtime.getRuntime().exec(command);

I am new to java..... I have 3 files in the zip folder, which I m extracting it using
String command = "cmd /c start cmd.exe /K \"jar -xvf record.zip\"";
Process ps= Runtime.getRuntime().exec(command);
I need to store all the three files present in record.zip into a String after extracting
these files using jar -xvf
BufferedReader br=new BufferedReader(new InputStreamReader(ps.getInputStream()));
String temp = br.readLine();
while( temp != null ) { //!temp.equals(null)) {
output.write(temp);
temp = br.readLine();
}
output.close();
I tried this code but it doesn't fetch me the desired result....
Thanks in advance....
You can use the functionality already in the JDK to read from zip files, for example this will print the contents of all files in a zip to the console line by line:
public static void main(String[] args) throws ZipException, IOException {
final File file = new File("myZipFile.zip");
final ZipFile zipFile = new ZipFile(file);
final Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
final ZipEntry entry = entries.nextElement();
System.out.println(entry);
if (!entry.isDirectory()) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry)));
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
System.out.println(line);
}
}
}
zipFile.close();
}

Categories