where does the saved file go java - java

I have a method
public void save(String filename)
{
try
{
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filename)));
for(Track item : thePlayList)
{
item.save(bw);
}
bw.close();
}
catch (Exception e)
{
System.out.println("couldn't save M3U file " + filename);
}
and I have this in the main method, I would like to know where does the saved file go ? if not then how to save the file in a specific folder.
combine.save("combined");

When specified without a path, Java is going to write the file into the working directory. You can always determine where that is with something like this
File file = new File(filename);
System.out.println(file.getCanonicalPath()); // <-- should print the full path to the file
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
You can also specify a full path when you call your method, for example -
combine.save("C:/combined"); // <-- or C:\\combined
or a relative path, for example -
combine.save("./output/combined"); // <-- or ../output/combined

The file will be saved in within the execution context of the application - in other words, the directory you ran it from...
For example...
If you ran the program from C:\MyJavaProgram, then it will be saved within this directory

Related

Writing to a JSON file with Java doesn't work after export

When I use my program within Eclipse everything works flawlessly, the JSON file is saved between launches. The problem occurs when i export the project to a Runnable Jar File, the saving of the JSON file no longer works, at all. I can still read from the file, but it doesn't save it.
Here is the "writing/saving" code I've written.
/*
* Write to character JSON file
*/
public void saveCharacterInfo() {
JSONObject obj = JSONUtils.getJSONObjectFromFile("/character.json");
obj.put("day", c.getDay());
obj.put("name", c.getCharName());
obj.put("hp", c.getCharHp());
obj.put("maxHp", c.getCharHpMax());
obj.put("armor", c.getCharArmor());
obj.put("speed", c.getCharSpeed());
obj.put("strength", c.getCharStrength());
obj.put("money", c.getCharMoney());
obj.put("food", c.getCharFood());
obj.put("maxFood", c.getCharMaxFood());
obj.put("morale", c.getCharMorale());
obj.put("bait", c.getCharBait());
try {
URL resourceUrl = getClass().getResource("/character.json");
File file = new File(resourceUrl.toURI());
FileWriter writer = new FileWriter(file);
writer.write(obj.toString());
writer.flush();
writer.close();
} catch (Exception e) {
}
}
Since outside Eclipse neither the bin nor the file itself haven't been created yet, you have to create it, at first and if there was a file before, since we want to overwrite it, we use the delete method before creating it. So the whole changes are written here:
public void saveCharacterInfo() {
JSONObject obj = JSONUtils.getJSONObjectFromFile("/character.json");
obj.put("day", c.getDay());
obj.put("name", c.getCharName());
obj.put("hp", c.getCharHp());
obj.put("maxHp", c.getCharHpMax());
obj.put("armor", c.getCharArmor());
obj.put("speed", c.getCharSpeed());
obj.put("strength", c.getCharStrength());
obj.put("money", c.getCharMoney());
obj.put("food", c.getCharFood());
obj.put("maxFood", c.getCharMaxFood());
obj.put("morale", c.getCharMorale());
obj.put("bait", c.getCharBait());
try {
URL resourceUrl = getClass().getResource("/character.json");
File file = new File(resourceUrl.toURI());
file.getParentFile().mkdirs();
file.delete();
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(obj.toString());
writer.flush();
writer.close();
} catch (Exception e) {
}
}
I tested it and the way to make the jar to create new folders is to execute it from the windows command console with:
java -jar jarName.jar
Or to create a bat file on the same folder.

Before creating the file , deleting the file of previous day

I am creating a dat file in C: drive folder named abc as shown below , Now my file is generated everyday
now suppose if my file is generated today, then tommrow it will be also generated as usual
but when tommrow it is generated I have to make sure that earlier day file is deleted as the space in that folder is limited and this check is every time need to be done previos day file to be get deleted from that folder , please advise how to achieve this..
File file = new File(FilePath + getFileName()); //filepath is being passes through //ioc //and filename through a method
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(
file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
fileOutput));
why not use file.delete() ?
File file = new File(FilePath + getFileName()); //filepath is being passes through //ioc //and filename through a method
if (file.exists()) {
file.delete(); //you might want to check if delete was successfull
}
file.createNewFile();
FileOutputStream fileOutput = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutput));
If your file name same in time to time no need to delete that. By running your code tomorrow, will over write file created today.
Consider following case
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\Test\test.txt"));
bw.write("abbbb");
bw.close(); // now this will create a test.txt in side Test folder
now run this by change writing String
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\test.txt"));
bw.write("hihi");
bw.close(); // now you can see file only containing hihi
You can change your code this way:
if (file.exists()) {
file.delete();
}
file.createNewFile();
And if it does not work, it's a matter of permission.
If you are using Java 7 then there is standard way to get file creation time, So that you can check if file is created in previous day and should be delete.
Path path = Paths.get("/filepath/");
BasicFileAttributes fileAttributes = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("creationTime:"+ fileAttributes.creationTime());

Using the FileWriter with a full path

I specified the full path of the file location when I created a FileWriter, but I did not see the file being created. I also did not get any error during file creation.
Here's a snippet of my code:
public void writeToFile(String fullpath, String contents) {
File file = new File(fullpath, "contents.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
bw.write(contents);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
fullpath is "D:/codes/sources/logs/../../bin/logs".
I have searched my whole directory, but I cannot find the file anywhere.
If I specify just the filename only [File file = new File("contents.txt");] , it is able to save the contents of the file, but it is not placed on my preferred location.
How can I save the file content to a preferred location?
UPDATE:
I printed the full path using file.getAbsolutePath(), and I am getting the correct directory path. [D:\codes\sources\logs....\bin\logs\contents.txt] But when I look for the file in directory, I cannot find it there.
Make sure you add trailing backslashes to the path parameter so the path is recognized as a directory. The example provide is for a Windows OS which uses backslashes that are escaped. For a more robust method use the file.separator property for the system.
Works
writeToFile("D:\\Documents and Settings\\me\\Desktop\\Development\\",
"this is a test");
Doesn't Work
writeToFile("D:\\Documents and Settings\\me\\Desktop\\Development",
"this is a test");
File Separator Example
String fs = System.getProperty("file.separator");
String path = fs + "Documents and Settings" + fs + "me" + fs
+ "Desktop" + fs + "Development" + fs;
writeToFile(path, "this is a test");

FileNotFoundException when using FileWriter

I am trying to write some message to text file. The text file is in the server path. I am able to read content from that file. But i am unable to write content to that file. I am getting FileNotFoundException: \wastServer\apps\LogPath\message.txt (Access Denied).
Note: File has a read and write permissions.
But where i am doing wrong. Please find my code below.
Code:
String FilePath = "\\\\wastServer\\apps\\LogPath\\message.txt";
try {
File fo = new File(FilePath);
FileWriter fw=new FileWriter(fo);
BufferedWriter bw=new BufferedWriter(fw);
bw.write("Hello World");
bw.flush();
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please help me on this?
Please check whether you can access the apps and LogPath directory.
Type these on Run (Windows Key + R)
\\\\wastServer\\apps\\
\\\\wastServer\\apps\\LogPath\\
And see whether you can access those directories from the machine and user you are executing the above code.
You don't have write access to the share, one of the directories, or the file itself. Possibly the file is already open.
After this line
File fo = new File(FilePath);
try to print the absolute path
System.out.println( fo.getAbsolutePath() );
And then check whether the file exists in that location, instead of directly checking at
\\\\wastServer\\apps\\LogPath\\message.txt
So , you will know, where the compiler is searching for the file.

Java - creating new file, how do I specify the directory with a method?

I know how to write a file to a specified directory by doing this:
public void writefile(){
try{
Writer output = null;
File file = new File("C:\\results\\results.txt");
output = new BufferedWriter(new FileWriter(file));
for(int i=0; i<100; i++){
//CODE TO FETCH RESULTS AND WRITE FILE
}
output.close();
System.out.println("File has been written");
}catch(Exception e){
System.out.println("Could not create file");
}
But how do I go on specifying the directory, if the directory is set in a method? A method called getCacheDirectory() for example. Assuming that all necessary imports etc have been done..
Thanks :).
You mean just
File file = new File(getCacheDirectory() + "\\results.txt");
That would be right if getCacheDirectory() returned the path as a String; if it returned a File, then there's a different constructor for that:
File file = new File(getCacheDirectory(), "results.txt");

Categories