I'm trying to decompress a rar file, using the runtime but it doesn't works!, just open a prompt saying that can't find the file
this is the code for it:
try {
Runtime.getRuntime().exec("C:\\Program Files (x86)\\WinRAR\\WinRAR.exe X *ok*.rar F:\\");
} catch (IOException ex) {
System.out.println(ex);
}
also i've used the processbuilder and that's worse, dosen't do anything ¬_¬
ProcessBuilder b = new ProcessBuilder("C:\\\\Program Files (x86)\\\\WinRAR\\\\WinRAR.exe X *sok*.rar F:\\");
here is where i find the information about the winrar
looks like path issue.( C:\Program Files (x86)\WinRAR\WinRAR.exe X ok.rar F:\")
"\" may be used along with roots eg(c:\, D:\) and then follows "\"
D:\programfiles\winar
Related
I'm trying to move an exe but I'm getting DirectoryNotEmptyException. Do I have to use another method or is there something I'm missing.
try {
Path rbx = Path.of(System.getProperty("user.dir")+"\\src\\test\\something.txt");
Path target = Path.of(System.getenv("LOCALAPPDATA")+ "\\toIt\\4ddd");
Files.move(rbx, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
Files.move isn't like the shell mv command. The 'target' has to include the actual file name. In other words, if your intent is for the something.txt file to cease being at ~/src/test/something.txt and start being at $LOCALAPPDATA/toIt/4ddd/something.txt, then you actually have to add something.txt to the target.
The reason you get this error is that the instruction you are running is telling the system: DELETE the entire 4ddd directory and once it is completely gone, make a text file named 4ddd. Which Files.move won't do, even if you use REPLACE_EXISTING.
My apologies if this is a duplicate, I've been searching around and haven't found anything that works.
I've been trying export a project as a JAR file that includes reading information from a text file. After doing some research, I changed my reader from FileReader to InputStreamReader, using CLASSNAME.class.getClassLoader().getResourceAsStream("textFile.txt"). (I also understand that it should work without the getClassLoader() method involved) However, getResourceAsStream("textFile.txt") returns null, throwing a NullPointerException when I try to read it using a BufferedReader.
From what I've read, this is because my text file isn't actually in the JAR. Yet when I attempt to do so I still get a NullPointerException. I've also tried adding the folder with the files to the build path, but that doesn't work either. I'm not sure how to check if the files are actually in the JAR and, if not, how to get them in the JAR so they can be found and properly read.
For reference, I currently use Eclipse Neon on a MacBook Air and here is my code that tries, but fails, to read the text file:
public static void addStates(String fileName) {
list.clear();
try {
InputStream in = RepAppor.class.getClassLoader().getResourceAsStream("Populations/" + fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
/*
* NOTE: A Leading slash indicates the absolute root of the directory, which is on my system
* Don't use a leading slash if the root is relative to the directory
*/
String line;
while(!((line = reader.readLine()) == null)) {
list.add(line);
}
reader.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "The file, " + fileName + ", could not be read.", "Error", JOptionPane.ERROR_MESSAGE);
} catch (NullPointerException n) {
JOptionPane.showMessageDialog(null, "Could not find " + fileName + ".\nNull Pointer Exception thrown", "Error", JOptionPane.ERROR_MESSAGE);
}
}
Thank you for your consideration and I appreciate and welcome any feedback you might have.
There are a number of ways to check the contents of a .jar file.
Most IDEs have a “Files” section where you can simply expand a .jar file, as if it were a directory.
If your have the JDK’s bin subdirectory in your execution path, you can use the jar command in a terminal:
jar tf /Users/AaronMoriak/repappor.jar
Every .jar file is actually a zip file with a different extension (and one or more Java-specific special entries). So, any command that handles zip files will work on .jar files.
Since you’re on a Mac, you have access to the Unix unzip command. In a terminal, you can simply do this:
unzip -v /Users/AaronMoriak/repappor.jar
(The -v option means “view but don’t extract.”)
If your .jar file has a lot of entries, you can limit the output of the above command:
unzip -v /Users/AaronMoriak/repappor.jar | grep Populations
Your code comment about a leading slash is not quite correct. However, if you remove the getClassLoader() part, the comment is somewhat more correct:
// Change:
// RepAppor.class.getClassLoader().getResourceAsStream
// to just:
// RepAppor.class.getResourceAsStream
// Expects 'Populations' to be in the same directory as the RepAppor class.
InputStream in = RepAppor.class.getResourceAsStream("Populations/" + fileName);
// Expects 'Populations' to be in the root of the classpath.
InputStream in = RepAppor.class.getResourceAsStream("/Populations/" + fileName);
I have two methods to obtain the jar path
1)
File file = new File(new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName());
String filename = file.getAbsolutePath().toString();
2)
String filename2 = Main.class.getProtectionDomain().getCodeSource().getLocation().toString().substring(6);
The first method works perfectly for windows and Mac, but in linux, if my jar is located at '/home/user/Documents/test folder/', it returns my current working directory + the jar file
Ex: If my terminal is at /home/user/, it returns /home/user/MyJar.jar even though MyJar.jar path is '/home/user/Documents/test folder/'.
The second method, for every operational system returns the correct path to the file but with spaces replaced by %20.
Ex: /home/user/Documents/test%20folder/MyJar.jar
How can I get the absolute path in Linux the same way I do for windows and Mac, and without %20 as space replacement?
I'm not sure why you've double wrapped your File's in the first solution.
try {
File f = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());
System.out.println(f.getAbsolutePath());
} catch (URISyntaxException ex) {
throw new RuntimeException(ex);
}
(Only tested under Linux)
(I don't think the URISyntaxException will ever be thrown in production)
Hello members of StackOverflow.
I am wanting to build a jar file in my java application with the following code:
private void javaToClass()
{
try {
String path = new File(".").getCanonicalPath();
String command = "cmd /c javac " + path + "\\files\\*.java";
System.out.println("Building class files...");
Runtime.getRuntime().exec(command);
System.out.println("Class files have been built");
} catch (IOException e) {
}
}
private void classToJar()
{
try {
String path = new File(".").getCanonicalPath();
String command = "cmd /c jar cf Built.jar " + path + "\\files\\*.class";
System.out.println("Building jar file...");
Runtime.getRuntime().exec(command);
System.out.println("Jar file has been built");
} catch (IOException e) {
}
}
So this builds the jar file but it doesn't add the class files to the jar file. Instead it will add my systems directory:
http://i.stack.imgur.com/cTrbO.png
So if anybody could explain to me how i would make it only add my class files it would be a great help.
Thanks.
Should jar command use -C parameter? Here is my jar syntax, where I give an explicit manifest file as well. You can leave that out and remove m option from options list.
jar cvfm ./lib/MyLib.jar ./classes/META-INF/MANIFEST.MF -C ./classes .
Another tip is you can use unix / path delimiter even in Windows for java commands and java fileio manipulations. Its a nice way keeping program Unix and Windows compatible.
Doublecheck working directory of shellexec process, you can give an explicit working dir(current dir). Or give an absolute filepaths to all file arguments (jarname, classes folder)
http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec%28java.lang.String[],%20java.lang.String[],%20java.io.File%29
You can do this using java.util.jar package.
http://docs.oracle.com/javase/6/docs/api/java/util/jar/package-summary.html
I am writing a program that needs to zip a file.
This will run over both linux and windows machines. It works just fine in Linux but I am not able to get anything done in windows.
To send commands I am using the apache-net project. I've also tried using Runtime().exec
but it isn't working.
Can somebody suggest something?
CommandLine cmdLine = new CommandLine("zip");
cmdLine.addArgument("-r");
cmdLine.addArgument("documents.zip");
cmdLine.addArgument("documents");
DefaultExecutor exec = new DefaultExecutor();
ExecuteWatchdog dog = new ExecuteWatchdog(60*1000);
exec.setWorkingDirectory(new File("."));
exec.setWatchdog(dog);
int check =-1;
try {
check = exec.execute(cmdLine);
} catch (ExecuteException e) {
} catch (IOException e) {
}
Java provides its own compression library in java.util.zip.* that supports the .zip format. An example that zips a folder can be found here. Here's a quickie example that works on a single file. The benefit of going with native Java is that it will work on multiple operating systems and is not dependent on having specific binaries installed.
public static void zip(String origFileName) {
try {
String zipName=origFileName + ".zip";
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipName)));
byte[] data = new byte[1000];
BufferedInputStream in = new BufferedInputStream(new FileInputStream(origFileName));
int count;
out.putNextEntry(new ZipEntry(origFileName));
while((count = in.read(data,0,1000)) != -1) {
out.write(data, 0, count);
}
in.close();
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
The same code won't work in Windows. Windows doesn't have a "zip" program the way that Linux does. You will need to see if Windows 7 has a command line zip program (I don't think it does; see here: http://answers.microsoft.com/en-us/windows/forum/windows_vista-files/how-to-compress-a-folder-from-command-prompt/02f93b08-bebc-4c9d-b2bb-907a2184c8d5). You will likely need to do two things
Make sure the user has a suitable 3rd party zip program
Do OS detection to execute the proper command.
You can use inbuilt compact.exe to compress/uncompress in dos
It displays or alters the compression of files on NTFS partitions.
COMPACT [/C | /U] [/S[:dir]] [/A] [/I] [/F] [/Q] [filename [...]]
/C Compresses the specified files. Directories will be marked so that files added afterward will be compressed.
/U Uncompresses the specified files. Directories will be marked so that files added afterward will not be compressed.
/S Performs the specified operation on files in the given directory and all subdirectories. Default "dir" is the current directory.
/A Displays files with the hidden or system attributes. These files are omitted by default.
/I Continues performing the specified operation even after errors have occurred. By default, COMPACT stops when an error is encountered.
/F Forces the compress operation on all specified files, even those that are already compressed. Already-compressed files are skipped by default.
/Q Reports only the most essential information.
filename Specifies a pattern, file, or directory.
Used without parameters, COMPACT displays the compression state of the current directory and any files it contains. You may use multiple filenames and wildcards. You must put spaces between multiple parameters.
Examples
compact
Display all the files in the current directory and their compact status.
compact file.txt
Display the compact status of the file file.txt
compact file.txt /C
Compacts the file.txt file.