I am working on a dynamic web project.
On submit button click (present on my form)I want to create a new file and put some data inside.
I have written only these two lines and I am getting failure to create file
try{
File file = new File("C:/database.txt");
file.createNewFile();
}catch(Exception e){
return "error in creating file";
}
If I run the enire code in normal java class everything works fine. Why so?
Your web project is working on application server. The web application can manage files, which are on that server. Other files are not accessible. (of course localhost server is on your computer, but that it's path is not "C:/", so you can't write there). You can find the path of your server running this code (it also create a test file):
String pathWhereYouFindYourFile = new File("").getAbsolutePath();
System.out.println(pathWhereYouFindYourFile);
File f = new File("test.txt");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Related
First of all i've tried my code by extracting the war file (using maven) on both eclipse and on a tomcat 8.0.33 stand alone on my mac.
I have also tried my code on a windows server 2008 with the same java version 1.8, and it works when i put some variable (which are username and password) hardcoded, but when i make the code to read them from a reousrce file, it is just working on my mac (both eclipse and tomcat stand alone), but not on the server
this is the code to read the resource
private static String getUsername() {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(MyConfiguration.class.getClassLoader()
.getResource("configuration.properties").getFile());
// load a properties file
prop.load(input);
// get the property value and print it out
return prop.getProperty("username");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
where the location of the configuration.properties is in the src/main/resources and on the server, i can see that file is in the correct directory.
i am using maven, i don't know what other information you need to help me, but if you say, i will give you
You may try
input = Thread.currentThread().getContextClassLoader().getResourceAsStream("configuration.properties");
Open your war and the jar file that contains your application. Ensure that the resource you are trying to open is in the jar (in the war) that is getting deployed. Most of the times this has happened to me, it's because I failed to tell my build process that this file needed to be copied over to the deployment. Class files go automatically, but not always resource files.
I'm using eclipse. I put a .pdf file in my src folder, i want to open it with the default OS program. The problem is that, if i execute the program with eclipse, i can open it (clicking on a MenuItem) like this :
File memo=new File("src/chap.pdf");
try {
Desktop.getDesktop().open(memo);
} catch (IOException e) {
e.printStackTrace();
}
However, after exporting the project to a jar file, this isn't working anymore. So is there a problem in my code or is there another way to get the file to open when it's in the jar file ?
The src path will not be available after you have exported your program and you should never reference it in any way.
You need to extract the resource from the Jar file and write it to the local disk...
try (InputStream is = getClass().getResourceAsStrea("/chap.pdf")) {
try (BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(...)) {
// Write contents like you would any file
}
} catch (IOException exp) {
exp.printStackTrace();
}
Then you can use the extracted file with Desktop
I have a program I have written in Eclipse and it runs fine -- the HTML file opens when I run the program through Eclipse. But when I create a jar file of the program, everything else runs fine except this HTML file won't open in the browser (or anywhere):
operation.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
File htmlFile = new File("help/operation.html");
Desktop.getDesktop().browse(htmlFile.toURI());
} catch (MalformedURLException MURLe) {
MURLe.printStackTrace();
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
});
The rest of the program runs fine, and my images and sounds work fine and are opened, but this HTML file will not open in the menu or with the Ctrl+key shortcut. Your help is appreciated. Thanks.
When you have a file inside your jar, you cannot access it like you are doing now.
You need to read it as a stream, that's the only way.
Suppose your project is foo. Then help/operation.html will refer to
..\abc\help\operation.html
But the deployed jar file will not contain it.
You have include this operation.html file in your source code (where you write code).
Then eclipse (or any IDE) will add it into your jar file when you deploy it.
And now you can use your file as follows.
Suppose your file is present in as shown in figure.
Now you can refer your html file from any class. In this example referring it from
Accesser class.
File resFile = new File(Accesser.class.getResource("operation.html").toURI());
If you want to open your file in browser you will have to copy this file into the
user's System.
File htmlFile = new File("operation.html");
if(!htmlFile.exists) {
Files.copy(resFile.toPath(), htmlFile.toPath());
}
Desktop.getDesktop().browse(htmlFile.toURI());
Files is present in java.nio.file package
Having a issue with getDeskTop().open / .edit(file) in that it is working properly on development drive by opening the file but when I move the application (jar) to another drive I get no error and no response. The paths are hardcoded "/home/temp/" + file, the application creates folders on start, basically the application is a personal version system serializes file contents to XML, when selected it deserializes then writes the file to a temp folder then calls getDeskTop().open(file). The confusing part is that I also call getDeskTop().open(file) on the VersionControl.xml that the app creates and it works properly, checked the path vars to the file and they are correct. Here is the basic call, I get the path vars from a JTable cell:
case 2 :
File fr = new File((String) jt.getModel().getValueAt(tmpRow, 2));
javaxt.io.File ft = new javaxt.io.File((String)jt.getModel().getValueAt(tmpRow, 2));
//JOptionPane.showMessageDialog(null, fr.toString());
if (!AppVars.getIllegalExt().contains(ft.getExtension())) {
try {
Desktop.getDesktop().edit(fr);
} catch (IOException e1) {
e1.printStackTrace();
}
}
break;
It seems somehow I am missing a reference, the "Make" configuration is to extract dependencies into the jar.
I tried to open file form my java application. Using following code from
Open PDF file on fly from Java application
Code:
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File("/path/to/file.pdf");
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
}
}
When I use path like :
"C:\\Users\\kalathoki\\Documents\\NetBeansProjects\\TestJava\\src\\files\\test.pdf"
it opens. But my file is inside my package
files/test.pdf
and I used
files\\test.pdf
it shows following exception:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: The file: \files\test.pdf doesn't exist.
Why? Any Idea... I want to include my file inside my jar file that can open from my application whenever user wants.
Thanks...
getDesktop#open only allows files to be opened from the file system. One solution is to keep the PDF file locally on the file system and read from there. This eliminates extracting the file from the JAR itself so is more efficient.
Unfortunately, you cannot load a file through Desktop that is contained in the jar.
However, you are not out of options. A great workaround is to create a temporary file and then open it as detailed here.
Good luck!
Assuming test.pdf is in the package files, try this:
File myFile = new File(getClass().getResource("/files/test.pdf").toURI());
This code is working properly please use this to open pdf file within jar file
try {
// TODO add your handling code here:
String path = jTextField1.getText();
System.out.println(path);
Path tempOutput = null;
String tempFile = "myFile";
tempOutput = Files.createTempFile(tempFile, ".pdf");
tempOutput.toFile().deleteOnExit();
InputStream is = getClass().getResourceAsStream("/JCADG.pdf");
Files.copy(is,tempOutput,StandardCopyOption.REPLACE_EXISTING);
if(Desktop.isDesktopSupported())
{
Desktop dTop = Desktop.getDesktop();
if(dTop.isSupported(Desktop.Action.OPEN))
{
dTop.open(tempOutput.toFile());
}
}
} catch (IOException ex) {}