I am working on a program that needs a lot of app data. I am trying to create a function that creates a file with the path/file name of the string path. Here's my code:
public static void CreateFile(String path) throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter(path, "UTF-8");
writer.close();
}
What did I do wrong? Shouldn't it create a file?
you can refer to this code :
FileWriter fw = new FileWriter("C:\\FileW3.txt");// you can give path here
//or
FileOutputStream fos = new FileOutputStream("path name");
PrintWriter pw = new PrintWriter (new OutputStreamWriter(fos));
pw.write("Combo stream and writer + using PrintWriter's write() methood/n");
pw.println();
pw.println("now using PrintWriter's println() methood");
pw.flush();
pw.close();
Also
File f = new File("path and filename");
This wont create a file , the file object can be used as parameter in FileWriter or FileOutputStream to create and then write to that file.
File object is just abstract representation of file.
It seems that you want to create an empty file. For this, you can use Files.createFile or File.createNewFile (but it will require you to instantiate a File).
To create a non-empty file, just write something in it and it will be automatically created if it does not exist.
Please see this link in the doucmentation - Create a file object then call 'createNewFile()' method on the newly created object.
Related
My current problems lie with the fact that no matter what solution I attempt at creating a file in Java, the file never, ever is created or shows up.
I've searched StackOverflow for solutions and tried many, many different pieces of code all to no avail. I've tried using BufferedWriter, PrintWriter, FileWriter, wrapped in try and catch and thrown IOExceptions, and none of it seems to be working. For every field that requires a path, I've tried both the name of the file alone and the name of the file in a path. Nothing works.
//I've tried so much I don't know what to show. Here is what remains in my method:
FileWriter fw = new FileWriter("testFile.txt", false);
PrintWriter output = new PrintWriter(fw);
fw.write("Hello");
I don't get any errors thrown whenever I've run my past code, however, the files never actually show up. How can I fix this?
Thank you in advance!
There are several ways to do this:
Write with BufferedWriter:
public void writeWithBufferedWriter()
throws IOException {
String str = "Hello";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(str);
writer.close();
}
If you want to append to a file:
public void appendUsingBufferedWritter()
throws IOException {
String str = "World";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(str);
writer.close();
}
Using PrintWriter:
public void usingPrintWriteru()
throws IOException {
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Some String");
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
printWriter.close();
}
Using FileOutputStream:
public void usingFileOutputStream()
throws IOException {
String str = "Hello";
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = str.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
Note:
If you try to write to a file that doesn’t exist, the file will be created first and no exception will be thrown.
It is very important to close the stream after using it, as it is not closed implicitly, to release any resources associated with it.
In output stream, the close() method calls flush() before releasing the resources which forces any buffered bytes to be written to the stream.
Source and More Examples: https://www.baeldung.com/java-write-to-file
Hope this helps. Good luck.
A couple of things worth trying:
1) In case you haven't (it's not in the code you've shown) make sure you close the file after you're done with it
2) Use a File instead of a String. This will let you double check where the file is being created
File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
FileWriter fw = new FileWriter(file, false);
fw.write("Hello");
fw.close();
As a bonus, Java's try-with-resource will automatically close the resource when it's done, you might want to try
File file = new File("testFile.txt");
System.out.println("I am creating the file at '" + file.getAbsolutePath() + "');
try (FileWriter fw = new FileWriter(file, false)) {
fw.write("Hello");
}
When you open an output file in Java, where does the name of the file get attached to the constructor if there is no field for it? Or does it just get attached to the file?
PrintWriter outputFile = new PrintWriter(fileName);
//Where does the filename go? I haven't had
//a good example of the outputfile's constructors in class
When passed a String (containing the intended file name) the PrintWriter constructor will internally create a FileOutputStream that is itself constructed using that file name.
It will then create an OutputStreamWriter that refers to the stream, retaining a (protected) reference to that writer, e.g. (in simplified form, without error checking):
protected Writer out;
public PrintWriter(String filename) {
OutputStream os = new FileOutputStream(filename);
out = new OutputStreamWriter(os);
}
All subsequent output is done via the out member variable, and the PrintWriter has no further use for the filename, hence why there's no member variable associated with it.
It's passed to the Outputstream you pass as a parameter for the Writer. Example:
try (final FileOutputStream fos = new FileOutputStream(new File("filename"))) {
final PrintWriter pw = new PrintWriter(fos);
}
The string you pass in the constructor is the full file' path, i.e. /data/my-file.txt.
If the file exists, you'll override its content. Otherwise, you'll create it and write inside it.
Here is another example:
FileWriter fstream;
try {
fstream = new FileWriter("1111.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write ("line 11111\r\n");
out.write("line 1222\r\n");
out.write("line 33\r\n");
out.close();
} catch (IOException e) {
// handle exception
e.printStackTrace();
}
I am wondering what the best way to clear a file is. I know that java automatically creates a file with
f = new Formatter("jibberish.txt");
s = new Scanner("jibberish.txt");
if none already exists. But what if one exists and I want to clear it every time I run the program? That is what I am wondering: to say it again how do I clear a file that already exists to just be blank?
Here is what I was thinking:
public void clearFile(){
//go through and do this every time in order to delete previous crap
while(s.hasNext()){
f.format(" ");
}
}
Best I could think of is :
Files.newBufferedWriter(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
and
Files.newInputStream(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
In both the cases if the file specified in pathObject is writable, then that file will be truncated. No need to call write() function. Above code is sufficient to empty/truncate a file.This is new in java 8.
Hope it Helps
You could delete the file and create it again instead of doing a lot of io.
if(file.delete()){
file.createNewFile();
}else{
//throw an exception indicating that the file could not be cleared
}
Alternately, you could just overwrite the contents of the file in one go as explained in the other answers :
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
Also, you are using the constructor from Scanner that takes a String argument. This constructor will not read from a file but use the String argument as the text to be scanned. You should first created a file handle and then pass it to the Scanner constructor :
File file = new File("jibberish.txt");
Scanner scanner = new Scanner(file);
If you want to clear the file without deleting may be you can workaround this
public static void clearTheFile() {
FileWriter fwOb = new FileWriter("FileName", false);
PrintWriter pwOb = new PrintWriter(fwOb, false);
pwOb.flush();
pwOb.close();
fwOb.close();
}
Edit: It throws exception so need to catch the exceptions
You can just print an empty string into the file.
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
type
new PrintWriter(PATH_FILE).close();
Better to use this:
public static void clear(String filename) throws IOException {
FileWriter fwOb = new FileWriter(filename, false);
PrintWriter pwOb = new PrintWriter(fwOb, false);
pwOb.flush();
pwOb.close();
fwOb.close();
}
I write a simple function like this:
private static void write(String Swrite) throws IOException {
if(!file.exists()) {
file.createNewFile();
}
FileOutputStream fop=new FileOutputStream(file);
if(Swrite!=null)
fop.write(Swrite.getBytes());
fop.flush();
fop.close();
}
Every time I call it, it rewrite and then I just get the last items that are written. How can I change it to not rewriting? The file variable is defined globally as a File.
On your FileOutputStream constructor, you need to add the boolean append parameter. It will then look like this:
FileOutputStream fop = new FileOutputStream(file, true);
This tells FileOutputStream that it should append the file instead of clearing and rewriting all of its current data.
Use constrctor which takes append flag as parameter.
FileOutputStream fop=new FileOutputStream(file, true);
you should open the file in append mode for this, by default FileOutputStream opens file in write mode. And you need not check for existence of file, it will be done implicitly by FileOutputStream
private static void write(String Swrite) throws IOException {
FileOutputStream fop=new FileOutputStream(file, true);
if(Swrite!=null)
fop.write(Swrite.getBytes());
fop.flush();
fop.close();
}
Try RandomAccessFile if your trying to write at certain byte offsets.
Tow parameter constructor is right. And it is redundant:
if(!file.exists()) {
file.createNewFile();
}
Constructor will do it for you.
I want to write in a file but in a way that it should not delete existing data in that file rather it should append that file. Can anybody please help by giving any example related to appending a file? Thank you
You should use the FileWriter(File file, boolean append) constructor with the boolean value true.
Example
File file = new File("c:/tmp/foo.txt");
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
pw.println("Hello, World");
pw.close();