How do I specify the path where I want to save my file when creating an output to a file in java?
//Set up Printer Output file
PrintWriter pw = new PrintWriter (new BufferedWriter (new FileWriter("project61.dat")));
For some reason after running my program, I don't see that my project61.dat file is created. I can't find anywhere in my C drive.
Simple google search yields helpful examples.
Here is one taken from here:
import java.io.IOException;
import java.io.PrintWriter;
public class MainClass {
public static void main(String[] args) {
try {
PrintWriter pw = new PrintWriter("c:\\temp\\printWriterOutput.txt");
pw.println("PrintWriter is easy to use.");
pw.println(1234);
pw.close();
} catch (IOException e) {}
}
}
If you use the following
//Set up Printer Output file
PrintWriter pw = new PrintWriter (new BufferedWriter (new FileWriter("project61.dat")));
Then it will create the file under your project. Please find the file where you project available.
If you want to write this file in a particular directory then mention the absolute path.
PrintWriter pw = new PrintWriter (new BufferedWriter (new FileWriter("c:\\project61.dat")));
pw.write("Test");
pw.close();
It will create the file under "C:" directory.
If you use the absolute directory "C://temp//project61.dat" then the temp folder must be available in c drive. The folder will not be created by default.
Related
I am using this method to write to a CSV file. Every time I run my code it removes all previous data from the file instead of adding to it.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
File dir = new File(".");
String loc = dir.getCanonicalPath() + File.separator + "Code.txt";
FileWriter fstream = new FileWriter(loc, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("something");
out.newLine();
//close buffer writer
out.close();
}
}```
You're better off using java.nio.file.Path, which opens up a lot of utility methods on java.nio.file.Files:
Path path = Path.of("Code.txt"); // Relative to current dir
Files.writeString(path, text, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
Where text is the content to append. Files.writeString is from Java 11+. For older versions you can use:
Files.write(path, text.getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);
I saved the text1.txt file in the same folder as the Algo.java file is in. But i get a Filenotfoundexception and i can't find any reason for that.
import java.io.*;
import java.util.logging.Level;
java.util.logging.Logger;
public class Algo{
static void naive(){
BufferedReader file1;
try{
file1=new BufferedReader(new FileReader("text1.txt"));
String T=file1.readLine();
System.out.println(T);
}
catch (FileNotFoundException ex) {
Logger.getLogger(Algoq1.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Algoq1.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String args[]){
Algo.naive();
}
}
Put resources separately form your code to make it manageable and reusable for other different package's classes also.
Try with other options.
// Read from same package
InputStream in = Algoq1.class.getResourceAsStream("text1.txt");
// Read from resources folder parallel to src in your project
File file = new File("resources/text1.txt");
// Read from src/resources folder
InputStream in = Algoq1.class.getResourceAsStream("/resources/text1.txt");
"I saved the text1.txt file in the same folder as the Algo.java file is in. But i get a Filenotfoundexception and i can't find any reason for that"
Then read the file from the class path. You can get an InputStream from Algo.class.getResourceAsStream()
InputStream is = Algo.class.getResourceAsStream("text1.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
When you try to read it as a File, which is the case when use FileReader(String path), file will be search within the file system, and in your IDE the search will begin from the working directory that is specified (normally the project root). So for the FileReader to work, with just the name of the file passed, the file should be in the working directory.
Depending on the requirements, whether the application is specific to your system or should be distributed on other systems, you need to make the decision whether the file should be read from the class path, or the file system.
I have this java code that download the .xml from my website and save it as an .xmlfile.
My problem is i want to save it into another folder.
When i run the code it downloads the file and saves it to the same folder where the java code is located.
I have searched about this and i cant find anything. Here is the code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;
public class dlxml {
public static void main(String[] args)
throws Exception {
URL url = new URL("http://localhost:8080/lab/lab.xml");
BufferedReader reader = new BufferedReader
(new InputStreamReader(url.openStream()));
BufferedWriter writer = new BufferedWriter
(new FileWriter("data.xml"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
}
}
So basically i want to download the file and save it to another folder. Is it possible?
and what if when i save it to a folder and there is the same file and name but i want to save it the same. For example i have data.xml save it to another folder but there is another same file with data.xml but i dont want it to be data(1).xml i want it to be data.xml
Thanks
Just define the folder path while writing to the file. As shown below:
BufferedWriter writer = new BufferedWriter(new FileWriter("\path\to\folder\data.xml"));
BufferedWriter writer = new BufferedWriter(new FileWriter(FULL_PATH));
In this code segment, you will want to change the file to use a path.
BufferedWriter writer = new BufferedWriter(new FileWriter("data.xml"));
By just using the name of the file, it will create the file in the relative directory (the same folder your code is running from) You'll want to change it to an absolute path so you can specify where you're storing it.
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
I want to write data to a text file. But, in my application, i will want to keep on writing items to the text file (Which means, the text that i want to write, should be appended to the file - and not create a new file every time)
My code, is as follows; But how could i append text the next time i am writing something to the file ?
1.) The problem with the code below is, the first time writes to the file, but when i am trying to write for the 2nd time i get the following exception;
java.io.IOException: Stream closed
2.) I want to be able to write to the same file untill the application is closed. Therefore, how can i close the Stream when the application is closed ?
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public void writeToFile(String stuff) {
try {
File file = new File("../somefile.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(stuff);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
UPDATE 1
private File file;
public WriteToFileExample(){
file = new File("../somefile.txt");
}
public void writeToFile(String stuff) {
try {
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(stuff);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
EXCEPTION
Exception in thread "main" java.lang.NullPointerException
at com.proj.example.Log.WriteToFile(WriteToFileExample.java:3)
Which points to if (!file.exists()) {.
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
Use the true argument for the FileWriter constructor.
You should create your FileWriter using the contructor that takes an extra boolean argument, that indicates that you want to append.
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
You never close the FileWriter in your code. And from the documentation for the class:
Whether or not a file is available or may be created depends upon the
underlying platform. Some platforms, in particular, allow a file to be
opened for writing by only one FileWriter (or other file-writing
object) at a time. In such situations the constructors in this class
will fail if the file involved is already open.
Close the file writer before exiting your method, its good practice anyway. And yes, definitely do open the writer in append mode, if you don't want the files contents to be blown away every time you call your method.
Checking the api, says that the FileWriter constructor takes a boolean to flag whether to append or not. That answer your question?
Instead of doing this:
FileWriter fw = new FileWriter(file.getAbsoluteFile());
do as follow:
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
As to append on a existing file FileWriter needs an extra argument as true here
FileWriter
public FileWriter(File file, boolean append) throws IOException
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be
written to the end of the file rather than the beginning.
Parameters:
file - a File object to write to
append - if true, then bytes will be
written to the end of the file rather than the beginning
Throws:
IOException - if the file exists but is a directory rather than a
regular file, does not exist but cannot be created, or cannot be
opened for any other reason
Since:
1.4