I need some help with using the following code to modify and existing jar file:
String command = "cmd /c jar uf " + dirToModify + " " + Main.getMain().outputLocate.getSelectedFile();
try {
Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
}
dirToModify = "C:\\Users\\Me\\Desktop\\myfile.jar"
Main.getMain().outputLocate.getSelectedFile() = "C:\\Users\\Me\\Desktop\\myfolder"
Basically I want to add the files/folders from myfolder to myfile.jar but with the above code it will add a shortcut to my C: drive not the files from myfolder.
Also I did look at other posts but none help me with this problem.
Any help with this would be greatly appreciated.
I'd suggest, first checking, if adding one file, at a time, is working with this code. This will make clear if problem is in 'folder addition' or 'file addition'.
If file addition doesn't work, your basic jar update logic is broken. So you can ask for solution to that problem.
If file addition works, try recursively adding all files from destination folder.
Related
I'm working on a project and part of it must search words in some raw files of tagged text. For this, I'm trying to use the "findstr" function but It's been giving me lots of trouble.
The file contains text in spanish so in order to deal with the special characters I have to use the "findstr" function with some options.
I'm trying to run the command by ProccesBuilder and Process class but nothing It's happening.
I suspected that maybe there was a problem with the actual work directory so I changed It in the ProcessBuilder object that I have but with no results.
private static void findWordData(String filename){
try{
String procs = "findstr /g:" + filename + " spanishEtiquetado* >results.txt";
ProcessBuilder proBuild = new ProcessBuilder();
proBuild.command("cmd.exe","/c",procs);
proBuild.directory(new File("resources/TextData/SPA/"));
Process p= proBuild.start();
} catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
The expected result is that the command reads the word in the file after the /g: tag and then searches it through all the files that begin with "spanishEtiquetado". Finally, the results should be written in a file "results.txt":
Thanks for your time.
EDIT:
Ok this is weird.
As you can read in the comments, I created a new project so I could test things better and something weird It's happening.
Right now, I have the aux_string.txt, results.txt and the spanishEtiquetado file both in the root folder of the project and src folder of the project.
As code I have been testing two options:
First, the one that SuperMario48 posted a bit modified:
Runtime.getRuntime().exec("cmd /c findstr /g:aux_strings.txt spanishEtiquetado* >results.txt");
The second one is the one I was using before:
String procs = "findstr /g:" + filename + " spanishEtiquetado* >results.txt";
ProcessBuilder proBuild = new ProcessBuilder();
proBuild.directory(new File("src/"));
proBuild.command("cmd.exe", "/c", procs);
Process p = proBuild.start();
If the first one is executed the files that are located in the root folder are treated by the command and thus the results.txt file in the root folder is modifided with the wanted results.
Now, If I use my old code the directory change happens and a results.txt is written in the src folder but it's empty because the other necesary files are not readed, not even those that are outside the src folder.
I don't hace any idea of what is happening, any help appreciated.
Maybe try this. Just another kind of executing an external process.
Runtime.getRuntime().exec("cmd /c findstr /g:" + filename + " spanishEtiquetado* >results.txt");
Replace your try block with that to test.
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 want to move files (images) from a folder to another:
For example:
/home/folder1/image.png
to
/home/folder1/folder2/image.png
And obviously remove the image from the folder1
I've trying to do it by reading the path and then modifying it, or using renameTo, but i can't do it.
I hope someone can help me a little with this, Thanks.
EDIT:
Well I can put the code but it's simple to explain what i did:
I just created a Folder class that has a File object of my folder (/home/folder1) , i read all the images inside and save it in an File array, then i scan it and try to change the path of every image file String to another
EDIT:
Thanks to all for the help, all are good examples, I was able to change my files to another location, there was a bunch of files I wanted to move so, I didn't want to create too many objects.
You said you tried renameTo and it didn't work, but this worked for me. After I renamed it I deleted the original file.
File a = new File("C:\\folderA\\A.txt");
a.renameTo(new File("C:\\folderB\\" + a.getName()));
a.delete();
In java 8+ you can simply use Files.move from nio:
try {
Path source = Paths.get("/home/folder1/image.png");
Path dest = Paths.get("/home/folder1/folder2/image.png");
Files.move(source, dest);
} catch (IOException e) {
...
}
The paths can even come from different file system providers (ie a ZipFileSystem).
Commons-io has a few methods in the FileUtils class that can help you.
http://commons.apache.org/proper/commons-io/javadocs/api-release/index.html?org/apache/commons/io/package-summary.html
Example:
FileUtils.moveFile(src, dest);
The usual approach to solving this is copying the file and then deleting it from the original location, but you can follow this tutorial for more information. Also, the platform(linux, windows, is not important).
I didn't run this, but it should work
File f1 = new File("/home/folder1/image.png");
File f2 = new File("/home/folder1/folder2/image.png");
f1.renameTo(f2);
There are many approaches for you to do that.
This snippet is one of them, you can move your files like this way:
try {
final File myFile = new File("C:\\folder1\\myfile.txt");
if(myFile.renameTo(new File("C:\\folder2\\" + myFile.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
What I need to do is get the name of the running jar/exe file (it would be an EXE on windows, jar on mac/linux). I have been searching around and I can't seem to find out how.
How to get name of running Jar or Exe?
Hope this can help you, I test the code and this return you the full path and the name.
Maybe you want to play a little more with the code and give me some feed back.
File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
This was found on a similar but not == question on stackoverflow
How to get the path of a running JAR file?
File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
returns simple path in the compiled application and an error in jar:
URI is not hierarchical
My solution is:
private File getJarFile() throws FileNotFoundException {
String path = Main.class.getResource(Main.class.getSimpleName() + ".class").getFile();
if(path.startsWith("/")) {
throw new FileNotFoundException("This is not a jar file: \n" + path);
}
path = ClassLoader.getSystemClassLoader().getResource(path).getFile();
return new File(path.substring(0, path.lastIndexOf('!')));
}
File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
Should give you the jar.
as for the exe, as I'm assuming you're using some sort of wrapper, you'll need to know the name of the exe before it's run. Then you could use something like :
Process p = Runtime.getRuntime().exec
(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
Try the following
System.getProperty("java.class.path")
Using Lunch4j you can add an image name for exe file by editing generated xml, you have to change tag value true from false to true
I am reading a file as follows:
File imgLoc = new File("Player.gif");
BufferedImage image = null;
try {
image = ImageIO.read(imgLoc);
}
catch(Exception ex)
{
System.out.println("Image read error");
System.exit(1);
}
return image;
I do not know where to place my file to make the Eclipse IDE, and my project can detect it when I run my code.
Is there a better way of creating a BufferedImage from an image file stored in your project directory?
Take a look in the comments for Class.getResource and Class.getResourceAsStream. These are probably what you really want to use as they will work whether you are running from within the directory of an Eclipse project, or from a JAR file after you package everything up.
You use them along the lines of:
InputStream in = MyClass.class.getResourceAsStream("Player.gif");
In this case, Java would look for the file "Player.gif" next to the MyClass.class file. That is, if the full package/class name is "com.package.MyClass", then Java will look for a file in "[project]/bin/com/package/Player.gif". The comments for getResourceAsStream indicate that if you lead with a slash, i.e. "/Player.gif", then it'll look in the root (i.e. the "bin" directory).
Note that you can drop the file in the "src" directory and Eclipse will automatically copy it to the "bin" directory at build time.
In the run dialog you can choose the directory. The default is the project root.
From my experience it seems to be the containing projects directory by default, but there is a simple way to find out:
System.out.println(new File(".").getAbsolutePath());
Are you trying to write a plugin for Eclipse or is it a regular project?
In the latter case, wouldn't that depend on where the program is installed and executed in the end?
While trying it out and running it from Eclipse, I'd guess that it would find the file in the project workspace. You should be able to find that out by opening the properties dialog for the project, and looking under the Resource entry.
Also, you can add resources to a project by using the Import menu option.
The default root folder for any Eclipse project is also a relative path of that application.
Below are steps I used for my Eclipse 4.8.0 and Java 1.8 project.
I - Place your file you want to interact with along the BIN and SRS folders of your project and not in one of those folders.
II - Implement below code in your main() method.
public static void main(String [] args) throws IOException {
FileReader myFileReader;
BufferedReader myReaderHelper;
try {
String localDir = System.getProperty("user.dir");
myFileReader = new FileReader(localDir + "\\yourFile.fileExtension");
myReaderHelper = new BufferedReader(myFileReader);
if (myReaderHelper.readLine() != null) {
StringTokenizer myTokens =
new StringTokenizer((String)myReaderHelper.readLine(), "," );
System.out.println(myTokens.nextToken().toString()); // - reading first item
}
} catch (FileNotFoundException myFileException) {
myFileException.printStackTrace(); } } // End of main()
III - Implement a loop to iterate through elements of your file if your logic requires this.