PrintWriter default location - java

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.

Related

java.io.FileNotFoundException: config.properties

I have a certain requirement where I need to copy files from Unix server to Windows Shared Drive. I am developing the necessary code for this in Java. I am a beginner so please excuse me for this basic question.
I have my source path in my config file. So, I am using the below code to import my config file and set my variable. My Project has config.properties file attached to it.
public static String rootFolder = "";
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Config files not able to set properly for Dest Folder");
}
try {
prop.load(input);
rootFolder = prop.getProperty("Dest_Root_Path");
System.out.println("Destination Folder is being initialized to - "+rootFolder);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Destination Path not set properly");
}
When I am doing this I am getting an error saying the file is not found.
java.io.FileNotFoundException: config.properties (No such file or directory)
at java.io.FileInputStream.<init>(FileInputStream.java:158)
at java.io.FileInputStream.<init>(FileInputStream.java:113)
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties.load(Properties.java:357)
I am triggering this jar using a unix ksh shell. Please provide guidance to me.
Put your config file somewhere within the classpath. For example, if it's a webapp, in WEB-INF/classes. If it isn't a webapp, create a folder outside the project, put the file there, and set the classpath so the new folder is in it.
Once you have your file in the classpath, get it as a resource with getResourceAsStream():
InputStream is = MyProject.class.getResourceAsStream("/config.properties");
Don't forget the slash / before the filename.

Making folder that will be accessable in jar

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";

Changes printed to a file aren't being saved

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"

Full path decleration for a file path used in java for jsp web app

I want to be able to have my paths work on any server not just my dev box.
Right now I declear the full path of the file name as such on my local drive.
filename = "H:\test\SourceCode\sample\src\file.txt"
try
{
BufferedReader in = new BufferedReader(new FileReader(fileName));
line = in.readLine();
in.close();
}
catch (IOException e) {
log.error("Exception Message", e);
}
How can I set the file path so when I create the .war file I can use it on any server. Such as filename = "src/file.txt" (This doesn't work for me)
Two usual ways:
getClass().getResourceAsStream("/..") - resolves the path relative to the classpath - that is, WEB-INF/classes (and jar files)
getServletContext().getResourceAsStream("/..") resolves the path relative to the webapp root. That is - webapps/applicationname

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.

Categories

Resources