I have a code to archive a ZIP file into another ZIP file, using command like this:
String rootftp = "C:\\ROOT_DIR_PUSHFILE\\";
String tampungString = "AAA\\PFILE\\AAA20140531.zip";
String password = "testing";
String command = "cmd.exe "
+ "/C"
+ " cd C:\\Program Files\\WinRAR \n"
+" && rar a -n "+rootftp.trim()+tampungString+".zip"+" "+ rootftp.trim()+tampungString + " -p"+password.trim();
System.out.println(command);
File file = new File(rootftp.trim()+tampungString);
try {
Runtime.getRuntime().exec(command);
file.delete();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
But the result is :
When I try to archive a specific file, the results is always archive from root directory, not just the specific file, like AAA20140531.zip file, can you explain, why? And how to fix it?
Use this command to create .rar without parent folder:
rar a -ep1 c:\ROOT_DIR_PUSHFILE\AAA\PFILE\AAA20140531.zip c:\ROOT_DIR_PUSHFILE\AAA\PFILE\ -p123456
-ep1 switch makes the result to exclude the base folder from the paths,
Related
I have a spring-boot application and I have some files placed inside /src/main/java/resources which I am trying to read it in my code. When the same code tries to read from docker container it says file does not exist. The same code works perfectly fine via localhost
The files are under /src/main/java/resources/data folder and this is my code which tries to read the file
private String getJson(String folderName, String id, StringBuilder sb) throws Exception {
String responseJson = null;
String filePath = "data" + File.separator + folderName + File.separator + id + ".json";
LOG.info("printing filePath : " + filePath);
LOG.info("printing id : " + id);
File f = new File(filePath);
// if(f.exists()){
try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath)) {
LOG.info("printing inputStream : " + inputStream);
if (inputStream != null) {
responseJson = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
}
if (responseJson == null || responseJson.isEmpty()) {
LOG.info("json response is null : ");
throw new JsonNotFoundException(Constant.JSON_NOT_FOUND);
}
sb.append(responseJson);
} catch (IOException e) {
LOG.info("IO exception : ");
throw new IOException(e);
} catch (Exception e) {
LOG.info(" exception : ");
throw new Exception(e);
}
// }
// else{
// LOG.info("file doesnt exists : " + filePath);
// }
return sb.toString();
}
An example for the file path : src/main/resources/data/get-products/1420-17612-82.json
Docker file content
{
"commands":
[
"rm -rf .tmp",
"git clone git#github.com:{orgnname}/{test-service.git} -b COECP-973-Configure-logging-mechanism-for-Service .tmp/test-service",
"docker build .tmp/test-service/.docker/build/db -t local/test-service/db",
"docker build .tmp/test-service -t local/test-service/app"
]
}
So... you messed path for File and for resources from class path. What is the reason to have File f = new File(filePath);?
Here are things:
If you use File - files must be available to the JVM and as long as you use relative path like data\folderxxx\filexxx.json it must be available in container file system. I.e. data folder must be placed in image or mounted from outside exactly into directory from where JVM runs
If you use ClassLoader and ResourceAsStream root of your data directory must be defined in class path for JVM or be in Jar file - it is a root in classpath as well. Check your jar file - if data directory is in root of jar - all fine and files will be available by this.getClass().getClassLoader().getResourceAsStream(filePath), but not for new File(filePath)!
if not - make it happen or update your filePath for ResourceAsStream accordingly.
I have had faced the same issue earlier, though our requirement got more complex over time, but the following code should solve your problem:
ClassPathResource cp = new ClassPathResource("relative_path_to_file");
File f = null;
if (cp.exists())
f = cp.getFile();
I am running java program from cmd like this java Main. But before that, I have to get to the route directory using cd ..., because my Main class is reding values from property file, which is in root directory. Is there a way or an option of setting the root directory, so then I will no need to get to this directory with cd commands ?
You could pass path to the directory as a parameter and get in from String[] args in main method. You'll pass absolute path to the file and it wouldn't be relevant from which directory you're starting your java process.
Here is the oracle's tutorial showing how you could do that.
Navigating to the directory through command prompt is very easy using a while loop and some simple String processing:
System.out.println("Please navigate to the desired directory then type 'done'...");
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
StringBuilder path = new StringBuilder(); //Storage for dir path
path.append(System.getenv("SystemDrive"));
while(scanner.hasNextLine()) {
String command = scanner.nextLine(); //Get input
if(command.equalsIgnoreCase("done")) {
break;
}else if(command.startsWith("cd")){
String arg = command.replaceFirst("cd ", ""); //Get next dir
if(!arg.startsWith(System.getenv("SystemDrive"))) { //Make sure they are not using a direct path
if(!new File(path.toString() + "/" + arg).exists()) { //Make sure the dir exists
arg = arg.equalsIgnoreCase("cd") ? "" : arg;
System.out.println("Directory '" + arg + "' cannot be found in path " + path.toString());
}else {
if(arg.equals("..."))
path = new StringBuilder(path.substring(0, path.lastIndexOf("/"))); //StringBuilder#substring does not alter the actual builder
else
path.append("/" + arg);
System.out.println("\t" + path.toString()); //Add the dir to the path
}
}else { //If they are using a direct path, delete the currently stored path
path = new StringBuilder();
path.append(arg);
System.out.println("\t" + path.toString());
}
}else if(command.equalsIgnoreCase("dir")) {
System.out.println(Arrays.toString(new File(path.toString() + "/").list()));
//List the dirs in the current path
}else {
System.out.println("\t" + command + " is not recognized as an internal command.");
}
}
//Get your file and do whatever
File theFile = new File(path.toString() + "/myFile.properties");
You could use the -cp (classpath) command-line argument of Java.
Then if your directory structure is
<application folder>
|
|--config.props (properties file)
|
\--bin
|
|--Main.class
|
|... other classes
You could just go to the <application folder> and use java -cp bin Main to start the application. And it could refer to config.props as a file in the current folder (because it is in the current folder).
As this is something what you may not want to type all the time, it could be wrapped in a Windows .bat file or *nix .sh script, residing in , next to config.props.
I specified the full path of the file location when I created a FileWriter, but I did not see the file being created. I also did not get any error during file creation.
Here's a snippet of my code:
public void writeToFile(String fullpath, String contents) {
File file = new File(fullpath, "contents.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
bw.write(contents);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
fullpath is "D:/codes/sources/logs/../../bin/logs".
I have searched my whole directory, but I cannot find the file anywhere.
If I specify just the filename only [File file = new File("contents.txt");] , it is able to save the contents of the file, but it is not placed on my preferred location.
How can I save the file content to a preferred location?
UPDATE:
I printed the full path using file.getAbsolutePath(), and I am getting the correct directory path. [D:\codes\sources\logs....\bin\logs\contents.txt] But when I look for the file in directory, I cannot find it there.
Make sure you add trailing backslashes to the path parameter so the path is recognized as a directory. The example provide is for a Windows OS which uses backslashes that are escaped. For a more robust method use the file.separator property for the system.
Works
writeToFile("D:\\Documents and Settings\\me\\Desktop\\Development\\",
"this is a test");
Doesn't Work
writeToFile("D:\\Documents and Settings\\me\\Desktop\\Development",
"this is a test");
File Separator Example
String fs = System.getProperty("file.separator");
String path = fs + "Documents and Settings" + fs + "me" + fs
+ "Desktop" + fs + "Development" + fs;
writeToFile(path, "this is a test");
I am using icefaces to upload files to relative path in my web app (mywebapp/audio), then after the file is getting uploaded I rename it to save its extension as follows:
public static File changeExtToWav(FileInfo fileInfo,
StringBuffer originalFileName) {
log.debug("changeExtToWav");
int mid = fileInfo.getFile().getName().lastIndexOf(".");
String fileName = fileInfo.getFile().getName().substring(0, mid);
originalFileName.append(fileName);
log.debug("originalFileName: " + originalFileName);
String newFileName = fileName + "_" + new Date().getTime() + "."
+ "wav";
File newFile = new File(fileInfo.getFile().getParent() + "/"
+ newFileName);
log.debug("newFileName: " + newFile.getName());
fileInfo.getFile().renameTo(newFile);
return newFile;
}
after the file is getting uploaded, sometimes I want to delete it from UI button as follows:
try {
File fileToDelete = new File(filePath); // correct file path
log.debug("file exists: " + fileToDelete.exists()); // true
fileToDelete.delete();
} catch (Exception e) {
e.printStackTrace();
}
the file path is correct, and I get no exceptions, but the file is not deleted (I am using java 6 btw).
please advise how to fix this issue.
UPDATE: using the following useful method, I can get that the file is opened, any ideas how to close it ?
public String getReasonForFileDeletionFailureInPlainEnglish(File file) {
try {
if (!file.exists())
return "It doesn't exist in the first place.";
else if (file.isDirectory() && file.list().length > 0)
return "It's a directory and it's not empty.";
else
return "Somebody else has it open, we don't have write permissions, or somebody stole my disk.";
} catch (SecurityException e) {
return "We're sandboxed and don't have filesystem access.";
}
}
Well if the file is open, then there is two solutions :
You have a stream in your program open on this file. Note that afaik it's a problem on Windows, with Unix I can delete a File even if a stream is opened on it.
You have an other process using this file. So in this case you can't do anything from Java.
In the log it tells also that it can be a permission problem, are you sure you have enough privileges?
You can also use Files#delete(Path path) (jdk7) to have more details about the issue.
I have a desktop application using Swing library. Application is running a batch file. So I created a lib folder in main project directory and put batch file in it. To run this, I am showing lib\a.exe to run this. It is working on my laptop. I exported .jar and put lib folder next to it. It is working on my laptop, but not working on some other laptops. How to fix this?
Error message is: Windows cannot found lib\a.exe.
String command = "cmd /c start lib\\a.exe";
try {
Runtime.getRuntime().exec(command);
increaseProgressBarValue();
} catch (IOException e) {
e.printStackTrace();
}
You need two things:
find the directory of the jar file of your application
call a.exe with the correct working directory
You can get the location of the jar with the getJar method below:
private static File getJar(Class clazz) throws MalformedURLException {
String name = clazz.getName().replace('.','/') + ".class";
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL url = cl.getResource(name);
System.out.println(url);
if (!"jar".equals(url.getProtocol())) {
throw new MalformedURLException("Expected a jar: URL " + url);
}
String file = url.getPath();
int pos = file.lastIndexOf('!');
if (pos < 0) {
throw new MalformedURLException("Expected ! " + file);
}
url = new URL(file.substring(0, pos));
if (!"file".equals(url.getProtocol())) {
throw new MalformedURLException("Expected a file: URL " + url);
}
String path = url.getPath();
if (path.matches("/[A-Za-z]:/")) { // Windoze drive letter
path = path.substring(1);
}
return new File(path);
}
To call lib\a.exe, you can do something like this:
File jar = getJar(MyClass.class); // MyClass can be any class in you jar file
File dir = jar.getParentFile();
ProcessBuilder builder = new ProcessBuilder();
builder.command("lib\\a.exe");
builder.directory(dir);
...
Process p = builder.start();
...
Maybe you have to try if this folder lib exists and if it doesn't than create it with
file.mkdir();
This is a just a checking. But your filepath must be like this ../lib/a.exe.