I want an option that when ever user selects autologin option...My program will make a folder and it will save a file in it...when the program will start it will look for folder and than file inside it. Problem is when i run my code via netbeans it is running perfectly but when i run it through jar it do not find any folder. Any body can guide me, what is best way to make a folder at run time and access it.
Down is my file writing code...
private void writeSerializableUserObject(boolean isAutoLogin , boolean isAutoRemember){
SerializableUser serializeUserObj = new SerializableUser();
serializeUserObj.setUserEmail(TempSessionUser.getTempUser().getEmail());
serializeUserObj.setUserPassword(TempSessionUser.getTempUser().getPassword());
serializeUserObj.setUserName(TempSessionUser.getTempUser().getF_name());
serializeUserObj.setIsAutoLogin(isAutoLogin);
if(isAutoRemember){
serializeUserObj.setIsAutoRemember(true);
}
System.out.println("in side method.......");
Edit
String path = System.getProperty("user.home");
File file = new File(path+"/user.ser");
if(!file.exists()){
file.mkdir();
}
try {
FileOutputStream fileOutPut = new FileOutputStream(file);
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(fileOutPut);
oos.writeObject(serializeUserObj);
oos.flush();
oos.close();
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}//Inner catch statment end
} catch (FileNotFoundException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}//Outer Catch statment end
}
After editing it is giving me this exception...within netbeans execution.her uptill HaseebAimal is my home directory path
java.io.FileNotFoundException: C:\Users\HaseebAimal\UserData\user.ser (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
at java.io.FileOutputStream.<init>(FileOutputStream.java:145)
getClass().getResource("/UserData") gives you a location in the class path which sometimes (usually) isn't a directory in the file system. Instead, you should probably pick one or more of:
Prompt the user for a save location.
Use a default location of some file or folder in the user's home directory, which you can get with System.getProperty("user.home").
Save it in the current working directory, which you can get with System.getProperty("user.dir").
The last option is probably the worst unless you know what the working directory will always be because you've handled the installation of your app in some way.
Before creating the FileOutputStream check what do file.canRead() and file.canWrite() return.
You need to make sure that the application can write to the location. If you do not have access to the location, try changing the directory to something else where you have write access.
Something like:
String path = "D:/test";
Related
I have create folder (i.e uploads ) in web application. I want to create one more folder inside "uploads" folder at runtime depends one the username of user. for this i have write below code. This code is creating folder and file but the location is different that i expected.
the location that i am getting is in eclipse location not web application location
D:\PAST\RequiredPlugins\JUNO\eclipse\uploads\datto\adhar.PNG
then i am getting error in FileOutStream that "system can't find the location specified."
public String getFolderName(String folderName, MultipartFile uploadPhoto)
throws ShareMeException {
File uploadfFile = null;
try {
File file = new File("uploads\\" + folderName);
if (!file.exists()) {
file.mkdir();
}
uploadfFile = new File(file.getAbsoluteFile()
+ "\\"+uploadPhoto.getOriginalFilename());
if (uploadfFile.exists()) {
throw new ShareMeException(
"file already exist please rename it");
} else {
uploadfFile.createNewFile();
FileOutputStream fout = new FileOutputStream(uploadfFile);
fout.write(uploadPhoto.getBytes());
fout.flush();
fout.close();
}
} catch (IOException e) {
throw new ShareMeException(e.getMessage());
}
return uploadfFile.getAbsolutePath();
}
i want to save uploaded file in web app "uploads" folder
Your filename is not absolute: uploads\folderName is resolved against the current directory, which the Eclipse launcher sets to JUNO\eclipse.
You should introduce an application variable like APP_HOME and resolve any data directory (including upload) against this variable.
Also, I suggest not to name anything (neither files nor directories) on your filesystem after user-entered input: you are asking for troubles (unicode characters in the user name) and especially security holes (even in combination with the unicode thing). If you really want to use the filesystem, keep the filename anonymous (1.data, 2.data, ...) and keep metadata inside some database.
You can do something on below lines in your webapp:-
String folderPath= request.getServletContext().getRealPath("/");
File file = new File (folderPath+"upload");
file.mkdir();
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 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) {}
I'm trying to write to a file. The code runs without an error, but I can't find the file anywhere. Not in the execution path, desktop, home folder, root folder.
Of course I could specify absolute paths, but I'm trying to figure out what a relative path is relative to, because I've seen examples like this.
try {
PrintWriter out = new PrintWriter ("example.txt");
out.print("test");
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
The file exists is in the current application path as indicated by new File("example.txt").getAbsolutePath()
Have you checked the java.io.tmpdir? It may be defaulting to that location. It is a System property.
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.