Running txt files in different editors by just writing programms name - java

i got two questions.
Where is the directory the Method Runtime.getRuntime().exec() gets its resources from?
if i am calling Runtime.getRuntime().exec("notepad.exe"), why does it start the windows editor? Where does java gets the .exe source from?
based on this question, i have to let the user choose, if he wants to open a file in an editor, which editors he prefers, and wants to use. He only writes in something like notepad.exe or ultraedit.exe and the choosen file will be opened in the editor written down here. At the moment, i am opening a file with this Method
public void open(String path) {
try {
if(new File(path).exists())
Runtime.getRuntime().exec("notepad.exe " + path);
} catch (IOException e) {
e.printStackTrace();
}
}
So as you can see every file will be opened within the notepad. But i need to have something like this :
public void open(String program, String path) {
try {
if(new File(path).exists())
Runtime.getRuntime().exec(program + " " + path);
} catch (IOException e) {
e.printStackTrace();
}
}
So is there any possibility to open txt files in different editors, by just calling their
.exe file?

Where does java gets the .exe source from?
Its not about java. check the PATH environment variables in you Operating systems. It has the path for all the exe files.
Try this
1) open cmd
2) type c:\> echo %PATH%
the second will tell you the values of PATH variable
So is there any possibility to open txt files in different editors, by just calling their .exe file?
yes edit the PATH variable to include the path of you other editor's exe file ( use semicolon and then append the path to environment don't replace the existing string ), and the java program remains the same

Runtime.exec() gets its information from PATH. Any program found in there can be executed like you showed.

Related

Copying File In Current Working Directory is Not Working

private void copyFile() throws IOException {
Path destination;
String currentWorkingDir = System.getProperty("user.dir");
File fileToCopy = component.getArchiveServerFile();
if (path.contains(File.separator)) {
destination = Paths.get(path);
} else {
destination = Paths.get(currentWorkingDir + File.separator + path);
}
if (!Files.exists(destination)) {
try {
Files.createDirectories(destination);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
FileUtils.copyFileToDirectory(fileToCopy, new File(destination.toString()));
}
}
Basically what I'm trying to do here is copying a file in some location using the path provided in the class's constructor. The logic is like this:
If the path has file separator, I consider it a full path and copy the file at the end.
If the path doesn't have file separator, I copy the file in the working directory from which the .exe file was launched.
So far, only the first option works (the full path). For some reason, the working directory option is not working and I can't figure out why.
UPDATE: If I just change the following line:
String currentWorkingDir = System.getProperty("user.dir");
to
String currentWorkingDir = System.getProperty("user.home");
It works. So I'm guessing the problem is coming from user.dir? Maybe at runtime, the folder is already being used and as a result, it can't copy the file into it?
The weird thing is, I don't have any exceptions or error, but nothing happens as well.
UPDATE 2: I think the problem here is that I'm trying to copy a file which is embedded in the application (.exe file) that I'm executing during runtime, and java can't copy it while the current working directory is being used by the application.
UPDATE 3:
Since this copy method is used in an external library, I had to come up with another way (other than logs) to see the content of system property user.dir. So I wrote I little program to create a file and write in it the value return by the property.
To my surprise, the path is not where my application was launched. It was in:
C:\Users\jj\AppData\Local\Temp\2\e4j1263.tmp_dir1602852411
Which is weird because I launched the program from :
C:\Users\jj\workspace\installer\product\target\
Any idea why I'm getting this unexpected value for user.dir?

Java: store configuration variables in a file

I'm developing a program with NetBeans 8.0 and JavaFX Scene Builder 2.0 that need store some variables in a file, where admin users can modify it when needed, (like change server IP address, or a number value from a no editable textfield) and if they close and load again the program, the changes made in variables are kept. Like any settings section of a program.
I just try do it with the Properties file, but i have problems to store it in the same folder as .jar file. When the program execute the line new FileOutputStream("configuration.properties"); the file is created at root of the disk. As the folder of the file can be stored anywhere, i not know how indicate the right path.
Creating the properties file in the package of the main project and using getClass().getResourceAsStream("configuration.properties"); i can read it but then i can not write in for change values of variables.
Is there a better method to create a configuration file? Or properties file is the best option for this case?
My other question is whether it is possible to prevent access to the contents of the file or encrypt the content?
PD: I've been testing this part of the code in Linux operating system currently, but the program will be used in Windows 7 when ready.
If you use Maven, you can store your property files in your resources folder, say resources/properties/. When you need to load them, do this:
private Properties createProps(String name)
{
Properties prop = new Properties();
InputStream in = null;
try
{
in = getClass().getResourceAsStream(name);
prop.load(in);
}
catch (IOException ex)
{
System.err.println("failed to load \"" + name + "\": " + ex);
}
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
System.err.println("failed to close InputStream for \"" + name + "\":\n" + FXUtils.extractStackTrace(ex));
}
}
return prop;
}
Where name is the full path to your properties file within your resources folder. For example, if you store props.properties in resources/properties/, then you would pass in properties/props.properties.
I am not 100% sure if you can carry over this exact procedure to a non-Maven project. You'd need to instruct whatever compiler tool you are using to also include your property files.
As far as your final question goes, in regards to encrypting your properties, I would consider posting that as a separate question (after having done thorough research to try to discover an existing solution that works for you).
At last i found how obtain the absolute path from folder where is .jar file to create properties file in, and read/write it. Here is the code:
File file = new File(System.getProperty("java.class.path"));
File filePath = file.getAbsoluteFile().getParentFile();
String strPath = filePath.toString();
File testFile = new File(strPath+"/configuration.properties");
Tested in Ubuntu 13.04 And Windows 7 and it works.
For encrypt the properties values i found this thread that answer how do it.

How to create a working .jar for a java project w/ excel input and System.out.print output?

I created this java project that basically gets data from an user determined excel file and uses Syste.out.println() to display the results. It works as I want it to in eclipse, however when I exported is as a .jar file, it doesn't work properly. It prompts for the excel file location to be entered, however, does not display the output, not even an error. I do not know how to do it from the terminal so I'm running it by double-clcking it. Also, I want the user to choose any excel file they want, so what should they write down as the location when prompted to do so? Right now, the excel file is in the same directory as the project. So just the name of the excel file is enough input, but what if it is not in the directory, how do i show it's location then?
Thank you
First of all, in your JAR file the file META-INF/MANIFEST.MF must contain your main class (i.e. the class with the main() method), with a line like this:
Main-Class: mypackage.MyMainClass
Make sure your settings in Eclipse are generating this line when generating the JAR file.
You can run it from the terminal with java -jar yourapp.jar however I presume that you have some extra libraries you need to include in the classpath with the -cp switch.
The working directory is normally the directory from where you are running the application. If you want to specify a different path it has to be either relative to that, or absolute.
An absolute path in windows would be something like: "C:\mydatafolder\myexcelsheet.xls"
An absolute path in Unix would be something like: "/home/myaccount/mydatafolder/myexcelsheet.xls"
You need to read System.in to get the file path, with a function like this:
private static String getFilePath () {
String filePath = null;
while (true) {
System.out.println("Please input the path of the file:");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
filePath = br.readLine();
File file = new File(filePath);
if (!file.exists()) {
System.out.println("Sorry, invalid file path. Please try again.");
} else {
return filePath;
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Sorry, unexpected error happened, Please try again.");
}
}
}

Writing to a file, where is the output file?

FileWriter outFile = null;
try {
outFile = new FileWriter("member.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println("test");
Running that command, where is the member.txt ? I am using windows vista. UAC enabled so when I run it, I don't think it's writing to the txt file. txt file is created however, but it's empty.
Relative paths in Java IO are relative to current working directory. In Eclipse, that's usually the project root. You're also writing to out instead of outFile. Here's a minor rewrite:
File file = new File("member.txt");
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("test");
} catch (IOException e) {
e.printStackTrace(); // I'd rather declare method with throws IOException and omit this catch.
} finally {
if (writer != null) try { writer.close(); } catch (IOException ignore) {}
}
System.out.printf("File is located at %s%n", file.getAbsolutePath());
Closing is mandatory since it flushes the written data into the file and releases the file lock.
Needless to say that it's a poor practice to use relative paths in Java IO. If you can, rather make use of the classpath. ClassLoader#getResource(), getResourceAsStream() and so on.
If the file is successfully created (no exception is raised), it is in the current working directory.
For the Java class you're executing, right click on the file and go to "Run As -> Run Configurations..."
In this screen, go to the "Arguments" tab. At the bottom of the screen, look for the "Working directory" setting. This is the directory that your Java class will run from.
In your example, you're creating "member.txt" in the current directory, so it will show up in whatever location your "Working directory" is set to.
It depends on the IDE you're using also. It will usually go into the same directory that the file.java is located at. I think programs like Eclipse and Netbeans may toss it in a different directory.
If running from Eclipse, the current working directory will be your project's base directory (view your project properties to find that location on disk). You should be able to see the file in the Project Explorer by refreshing the project (click on the project and hit F5).
You can specify an alternative working directory from the Run Configurations dialog under the Arguments tab.

How to Find Out Default File Opener with Java?

I need to find out default file opener for a given file on Windows so that I can customize the command arguments and open the file with the default opener/viewer.
My real usage scenario is opening multiple multimedia files with user's default media player so that all the files will be added to user's playlist (For the players that can open multiple files on the same intance). For operating system other than Windows I use Desktop.open(File file) method (I simply does not concern opening multiple files feature for OSs other than Windows), I cannot find any method which I can open multiple files other than customizing command arguments and running it using exec() method of the Runtime class. I use somethig similar to this:
private void playItems2(List<File> fileList, String playerBinary) {
String args = " ";
for (File file : fileList) {
args += "\"" + file.getAbsolutePath() + "\" ";
}
try {
String command = playerBinary + args;
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(command);
} catch (Exception exc) {/*handle exception*/
System.err.println("Run Player Exc:" + exc.getMessage());
}
}
I am using user specified path for the playerBinary, what I need to is automatically detecting default player for the first item of fileList and use it as playerBinary.
I have also looked at Rundll32.exe and cmd.exe /start solutions but they did not work for my usage scenario.
This question should not be confused with this and this.
Use this approach to call default opener and enjoy!
public void playItems2(...) throws Exception {
...
Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler c:/mp3/myfile.mp3");
p.waitFor();
...
}
Cannot do with pure Java alone.
In case of Windows, you need to read registry. Suppose you need to find out file association for .mp3
In the windows registry, look the default value for
HKEY_CLASSES_ROOT\.mp3. Usually its
"mp3file".
Now look for
HKEY_CLASSES_ROOT\mp3file\shell\open\command.
The value in there is a string
pointing to an executable to open
.mp3 files with.
Now this cant be done in Java, you need to choose appropriate 3rd party lib to do this for you.

Categories

Resources