copying directories using .jar program in java - java

i want to copy directories from the the place where my .jar files exist?
here are what i tried.. but i always get /home/user/
how can i copy files from where my .jar program exist?
private void copy_dir() {
//Path sourceParentFolder = Paths.get(System.getProperty("user.dir") + "/Project/");
// Path sourceParentFolder = Paths.get(Paths.get(".").toAbsolutePath().normalize().toString());
Path destinationParentFolder = Paths.get(System.getProperty("user.home"));
try {
Stream<Path> allFilesPathStream = Files.walk(sourceParentFolder);
Consumer<? super Path> action = new Consumer<Path>() {
#Override
public void accept(Path t) {
try {
String destinationPath = t.toString().replaceAll(sourceParentFolder.toString(), destinationParentFolder.toString());
Files.copy(t, Paths.get(destinationPath));
} catch (FileAlreadyExistsException e) {
//TODO do acc to business needs
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
allFilesPathStream.forEach(action);
} catch (FileAlreadyExistsException e) {
//file already exists and unable to copy
} catch (IOException e) {
//permission issue
e.printStackTrace();
}
}

Try
Path destinationParentFolder = Paths.get(System.getProperty("user.dir"));
"user.dir" gets the absolute path from where your application was initialized.
"user.home" gets the user's home directory.

Related

Is this incorrect use or bad practice of class loaders?

My program is designed to launch from a runnable jar file, set everything up if needs be, and then load a class in another jar file to initiate the program. This allows for self updating, restarts, etc. Well, the class loading code I have seems a bit funky to me. Below is the code I am using to do load the program. Is this incorrect use or bad practice?
try {
Preferences.userRoot().put("clientPath", Run.class.getProtectionDomain().getCodeSource().getLocation().toURI().toString()); //Original client location; helps with restarts
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
try {
Preferences.userRoot().flush();
} catch (BackingStoreException e1) {
e1.printStackTrace();
}
File file = new File(path); // path of the jar we will be launching to initiate the program outside of the Run class
URL url = null;
try {
url = file.toURI().toURL(); // converts the file path to a url
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL[] urls = new URL[] { url };
ClassLoader cl = new URLClassLoader(urls);
Class cls = null;
try {
cls = cl.loadClass("com.hexbit.EditorJ.Load"); // the class we are loading to initiate the program
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
cls.newInstance(); // starts the class that has been loaded and the program is on its way
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
The biggest problem you have is that when you get an Exception you pretend that logging the exception makes it ok to continue as if nothing happened.
If you aggregate the try/catch blocks, your code will be much shorter and easier to read, and it won't assume that exceptions don't really matter.
Try this example
public static Object load(String path, String className) {
try {
URL url = new File(path).toURI().toURL();
ClassLoader cl = new URLClassLoader(new URL[] { url });
return cl.loadClass(className).newInstance();
} catch (Exception e) {
throw new IllegalStateException("Unable to load "+className+" " + e);
}
}

Error in FileUtils.copyUrlToFile

I am executing the below code to pull the .gz file from a URL to a local directory.For small files it goes through fine but for large files it downloads only part of it but does not fail. I get to know the error only when I try to UNZIP it. Can someone throw any light on this on what could be the reason.
public boolean downloadFilemethod(String filePath, String url, String
decompressFilePath) {
if (StringUtils.isNotBlank(filePath) && StringUtils.isNotBlank(url)) {
try {
FileUtils.copyURLToFile(new URL(url), new File(SRC_BASE_DIR + filePath),
TIMEOUT_IN_MILLIS, TIMEOUT_IN_MILLIS);
ingestmethod(filePath,decompressFilePath);
downloadSuccess = true;
}
catch (MalformedURLException e)
{ LOG.warn("some message"); }
catch (IOException e)
{ LOG.warn("some message);
}
}
return downloadSuccess
}

How to open an exe file in java

I am trying to use java to open an exe file. I'm not sure which program I want to open so I am using Skype as an example. When I try to do it, it gives me errors.
try {
Process p = Runtime.getRuntime().exec("C:\\Program Files (x86)\\Skype\\Phone\\Skype");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
error:
Cannot run program "C:\Program": CreateProcess error=2, The system cannot find the file specified
Try this:
String path = "/path/to/my_app.exe";
File file = new File(path);
if (! file.exists()) {
throw new IllegalArgumentException("The file " + path + " does not exist");
}
Process p = Runtime.getRuntime().exec(file.getAbsolutePath());
You have to use a string array, change to
try {
Process p = Runtime.getRuntime().exec(new String[] {"C:\\Program Files (x86)\\Notepad++\\notepad++.exe"});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You are on windows so you have to include the extension .exe
try {
Process p = Runtime.getRuntime().exec("C:/Program Files (x86)/Skype/Phone/Skype.exe");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Maybe use File.separator instead of '\'
I tried this and it works fine, it's taken from your example. Pay attention to the double \\
public static void main(String[] args) {
try {
Process p;
p = Runtime.getRuntime().exec("C:\\Program Files\\Java\\jdk1.8.0_05\\bin\\Jconsole.exe");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

How can I create a directory in BlackBerry internal memory

I am trying to create a directory to store my application's files in the BlackBerry's internal memory. Here's the code:
String uri = "file:///store/testapp/";
FileConnection dir;
try {
dir = (FileConnection)Connector.open(uri, Connector.READ_WRITE);
if (!dir.exists()){
dir.mkdir();
}
dir.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
When I run the above I get an IOException with the message "File System Error (12)". Looking this up in the list of BlackBerry constant values this corresponds to "The operation requested is invalid.". Why can't I create the testapp directory?
You can create your own directories only in: "file:///store/home/user/"
You should only create directories in "file:///store/home/user/" or "file:///store/home/samples/" only;
For creating a directory:
public void createDirectory()
{
FileConnection file=null;
try
{
String Path="file:///store/home/user/Abc/"; // or path="file:///store/home/samples/Abc/"
file = (FileConnection)Connector.open(Path);
if(!file.exists())
file.mkdir();
file.close();
}
catch (IOException e)
{
try
{
if(file!=null)
{
file.close();
}
System.out.println("==============Exception: "+e.getMessage());
}
catch (IOException e1)
{
}
}
}
There is different in "file:///store/home/user/Abc/" and "file:///store/home/user/Abc"
If you put like "file:///store/home/user/Abc" then it take the "Abc" as file;
If you put like "file:///store/home/user/Abc/" then it take the "Abc" as directory;

Need help to find the filename

I used the following code to run an exe I load through my code.
private static String filelocation = "";
.
load_exe.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
JFileChooser file_Choose = new JFileChooser();
file_Choose.showOpenDialog(frame);
JavaSamp.filelocation = file_Choose.getCurrentDirectory()
.toString()
+ "\\" + file_Choose.getSelectedFile().getName();
System.out.println("FileLocation" + JavaSamp.filelocation);
} catch (Exception expobj) {
// TODO Auto-generated catch block
}
Runtime rt = Runtime.getRuntime();
try {
System.out.println("File Run Location" + JavaSamp.filelocation);
proc = rt.exec(JavaSamp.filelocation);
} catch (IOException e4) {
e4.printStackTrace();
} catch (Exception e2) {
}
}
});
My problem is, the above execution of the JavaSamp.filelocation, should have to done many times. First time only I load the exe. Next time I wont. I need to store the exe in a string to run for the successive times.
Any suggestion pls
If you want remember the used file just initialize the filelocation with null and test for it. BTW: Storing it as File makes more sense and your way of constructing the absolute path is a bit intricate - compared to just calling getAbsolutePath()
private static File filelocation = null;
private static void test() {
load_exe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Check if file-name to execute has already been set
if (filelocation != null) {
try {
JFileChooser file_Choose = new JFileChooser();
file_Choose.showOpenDialog(frame);
JavaSamp.filelocation = file_Choose.getSelectedFile();
System.out.println("FileLocation"
+ JavaSamp.filelocation.getAbsolutePath());
} catch (Exception expobj) {
}
}
Runtime rt = Runtime.getRuntime();
try {
System.out.println("File Run Location"
+ JavaSamp.filelocation.getAbsolutePath());
Process proc = rt.exec(JavaSamp.filelocation
.getAbsolutePath());
} catch (IOException e4) {
e4.printStackTrace();
}
}
};
}

Categories

Resources