Opening PDF only works in netbeans - java

I have written a program that creates PDF documents. After creating, the PDF's must be opened so it can be printen.
i have the following code, but it only works if i launch from netbeans. Could anyone give me some pointers?
public void openPDF()
{
try {
System.out.println("Opening PDF");
File file = new File(pdfPath+pdfName);
String absolutePDFpath = file.getAbsolutePath().replace(""+(char)92,""+(char)92+(char)9);
System.out.println("Path = "+absolutePDFpath);
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + absolutePDFpath);
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(null, "Er is een fout opgetreden tijdens het openen van het PDF"
+ " document\nFoutcode: 0xFF05");
Logger.getLogger(PrintJob.class.getName()).log(Level.SEVERE, null, ex);
}

See Desktop.open(File) for a way to open a PDF across different platforms. Something like this..
File file = new File(pdfPath+pdfName);
Desktop.getDesktop().open(file);
If the app. needs to support Java 1.5 or earlier (before Desktop was available), stick with exec(), but implement all the recommendations of When Runtime.exec() won't.
There are a number of things that using a Process requires the programmer to do, for reliable running. That code does none of them.

Probably your code doesn't work because you don't specify environment variables. It should be something like this:
Runtime.getRuntime().exec("command to execute", env[]);

Related

Android internal files seems to disappear after I restart my application

I am new to android and currently trying to save a few files in a little "play-around" application I am making to learn, however the files only seem to persist until the application is shut down. When I run:
file.exists()
file.isFile()
or any similar methods they always return false when the application is restarted.
This is the method I found online to save files:
public void writeToFile(String data, String filePath, Context context){
File file = new File(context.getFilesDir(), filePath);
if(!file.exists()){
try{
file.createNewFile();
}catch(IOException e) {
e.printStackTrace();
Log.e("Exception", "File couldn't be created");
}
}
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(filePath, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
I have been googling a lot trying to find a solution but none of them worked. It seems to work when the application is running since I can write and read the files, however at a restart of the application, it cannot find the files. (file.exists() returns false)
I just spend an hour tracking down this same bug and it turned out it was because the "Clear User Data" flag was set under "Deployment" in the project properties. I'm using NVIDIA CodeWorks for Android with Visual Studio 2017.
I assume that you are attempting to write to internal storage here? If not and you wish to access external storage, I would suggest having a look through the guidance on Android.com below.
https://developer.android.com/guide/topics/data/data-storage.html#filesInternal
If this is internal storage that you are trying to write to, then you need to make sure that you are passing the correct context to the method. For example, if you were running from your MainActivity class and the method was contained within that class, your call would be something along the lines of:
writeToFile("Some data", "aFile.txt", MainActivity.this)

Writing a file to a specific directory

I've created a simple program that would write a file with a directory using the following codes:
String nameProve = nameField.getText();
String employee = ("C:\\Users\\ALLEN\\workspace32bit\\RETRIEVE_CHECKER1\\RETRIEVE_CHECKED1" + nameProve + ".txt");
PrintWriter outputStream1 = null;
try
{
outputStream1 = new PrintWriter(employeeName);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Can not write to " + employeeName);
System.exit(0);
}
outputStream1.println("Employee Retrieve Executed");
outputStream1.close();
I've already exported my code to a .jar file and my code works just fine if i execute it in the computer were I've develop my program but when I copied the jar file to other computer and I also created the forlder (manually) that corresponds with the directory in my codes my program doesn't work and my catch block will show the message Can not write to "C:\Users\ALLEN\workspace32bit\RETRIEVE_CHECKER1\RETRIEVE_CHECKED1" + nameProve + ".txt"
Can anybody give me some advice on how to solve this error? Thanks!
Obviously you are the user ALLEN on your machine and run the program as that user, so everithing works fine, because you are the owner of the directory C:\Users\ALLEN.
Then you copy the jar to another machine, where the user ALLEN does not exist and you are logged in as antoher user let's say his name is Bob and create that directory unter C:\Users. You may have noticed that you when you wanted to create that directory as the user Bob windows has warned you that you need admin priviledges in order to compleate this action.
Now you try to run your program with the user Bob who has access only to his own directory C:\Users\Bob and try to write to ALLEN's own directory. So what happens is that you get an IOException telling you access denied which is good so!
You should not attepmt to write to other users private direcotries, this is a security issue.
In your code when dealing with filesystem, never hard code absolute path, always use relative paths, or if you need to defined a direcotry where all the data needed yb you program should be located, then pass ist as argument.
The simplest to do, ist use the following and work with the current working directory
String employee = "RETRIEVE_CHECKER1\\RETRIEVE_CHECKED1" + nameProve + ".txt";
You need to create the directory RETRIEVE_CHECKER1 either by hand in location where you run the program, or better yet in your program using File#mkdir and use it like this:
File employee = new File(dir, "RETRIEVE_CHECKED1" + nameProve + ".txt");
PrintWriter outputStream1 = new PrintWriter(employeeName);
Exception you catch will have all details- like access denied, directory not exist, etc. Currently you loose exception data (message, stacktrace) when catching it.
Please do something like
Do not catch just java.lang.Exception. This is too wide- will catch possible NullPointerException and present misleading message '"Can not write to'. Catch only specific exception instead- ones that are actually thrown from try block. In your case, that will be java.io.FileNotFoundException
Do not loose exception details. Print it to the standard error log, or even better use loging framework
catch block that adresses those issues:
catch(FileNotFoundException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
e.printStackTrace();
}

java open csv file using excel

I am making a project for college and have made a program which creates csv files. I would like there to be a button which you can click which then opens the csv file with excel. Thanks
Knowing that MsOffice is installed on the system, you should be able to open a document with it from command line using the command
excel myDoc.csv
to execute such a command from java, you could use this snapshot:
File myCSVFile; //reference to your file here
String execString = "excel " + myCSVFile.getAbsolutePath();
Runtime run = Runtime.getRuntime();
try {
Process pp = run.exec(execString);
} catch(Exception e) {
e.printStackTrace();
}
This is somewhat rough and needs styling, of course, but generally it should work. Besides, to be more graceful you could also check Windows registry, using the java.util.prefs.Preferences class, to know if MsOffice is installed and, if yes, where. But, please, be aware, if you are reckoning for MsExcel (as I understood from your post), this will automatically cancel Java's multiplatform approach. Hopefully, this helps :)
If you are using Java 6 you can use the Desktop class. Read also Opening, Editing, and Printing a File
You can use JExcel API. It will be very easy for you.
For whatever reason, execString's provided did not work for me, but the one below worked:
String execString = "cmd /c start excel \"" + filePathString + "\"";
With the other exeString's I kept getting an exception saying that the runtime cannot find the file - start or excel.

How can I excute Notepad by Java code

I want to open Notepad program in MS Windows by Java code to open my text file.
Pls help me to do that.
You can use the java.awt.Desktop if using Java 1.6, .txt is registered to the notepad and Desktop is supported:
if (!Desktop.isDesktopSupported()) {
System.err.println("Desktop not supported");
// use alternative (Runtime.exec)
return;
}
Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.EDIT)) {
System.err.println("EDIT not supported");
// use alternative (Runtime.exec)
return;
}
try {
desktop.edit(new File("test.txt"));
} catch (IOException ex) {
ex.printStackTrace();
}
this way you can open/edit files in a more OS independent way.
Runtime.getRuntime().exec("notepad c:/asd.txt");
where c:/asd.txt is the full path to your text file. If / doesn't work for you, use \\ instead.
If you have registered the .txt extension on your OS and your text file already exists then you can do even
Runtime.getRuntime().exec(new String[]{"cmd.exe","/c","text.txt"});
The advantage is it will take the program associated with .txt, what could be diferent from notepad.exe.
use the ProcessBuilder Class
Process p = new ProcessBuilder("notepad", "file.txt").start();

Opening an Excel file using the default program

My program successfully creates and fills a Excel(.xls) file. Once created, I would like the new file to open in the system's default program (Excel in my case). How can I achieve this?
For an older program where I wanted to open a txt file in Notepad, I used the following:
if (!Desktop.isDesktopSupported()) {
System.err.println("Desktop not supported");
// use alternative (Runtime.exec)
return;
}
Desktop desktop = Desktop.getDesktop();
if (!desktop.isSupported(Desktop.Action.EDIT)) {
System.err.println("EDIT not supported");
// use alternative (Runtime.exec)
return;
}
try {
desktop.edit(new File(this.outputFilePath));
} catch (IOException ex) {
ex.printStackTrace();
}
When I try to use this code for an Excel file it gives me the following error:
java.io.IOException: Failed to edit file:C:/foo.xls
Suggestions?
Try to use Desktop.open() instead of Desktop.edit() :
Desktop dt = Desktop.getDesktop();
dt.open(new File(this.outputFilePath));
If Desktop.open() is not available then the Windows file association can be used :
Process p =
Runtime.getRuntime()
.exec("rundll32 url.dll,FileProtocolHandler " + this.outputFilePath);
You probably did the Runtime.exec incorrectly. Give this a look to see if that's the case.
If you just want to open an Excel file with Java, I'd recommend using Andy Khan's JExcel API. Perhaps using that with a Swing JTable will be just the ticket.
The most simple and efficient way.
Desktop.getDesktop().open(new File("inputFilePath"));

Categories

Resources