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.
Related
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
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.
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";
try{
private fileWriter= new PrintWriter(new FileWriter(file.txt));
fileWriter.print("hello world");
System.out.println("file written");
fileWriter.close();
}
catch (IOException e){
e.printStackTrace();
} finally {
}
I have this text file in my source folder. So far, there haven't been any errors with accessing it. However, when I close the program or after when the files should have been written when I open the text file I don't find them there, however I did check the bin folder ocne and it seemed to print hello world to the temp copy there.
I want the changes it makes to be permanent.
You have a couple of problems in your code. Correcting/simplifying it to the following:
public static void main(String[] args) throws IOException {
PrintWriter fileWriter = new PrintWriter(new FileWriter(new File("file.txt")));
fileWriter.print("hello world");
System.out.println("file written");
fileWriter.close();
}
makes it create the file as expected. Try that out, and if it doesn't behave the way you're expecting, then explain how. Note that when you give a relative file path, it resolves the path against your current working directory. If the file is being written somewhere you don't expect, this is probably why.
The file in the bin folder is not a temp file, it is the file you are actually writing. If you want to write to the file in the source folder you have to use it's correct file path when opening the file for writing. Java always computes relative paths to the folder you started your application in. So your application is probably started in the bin folder and writes to file.txt there.
Maybe try using the append boolean in the FileWriter constructor
public FileWriter(String fileName, boolean append)
...and I think eclipse will use the bin folder as its default classpath so its no surprise the file is written there.
I hope that helps :)
Since the code was fine going to the package explorer --> project --> properties --> java build path --> source --> checking the box that says "allow outputs for source folders"