In Java we can create a reference to a file by...
File counterFile = new File("countervalue.txt");
but how do we create the file if it does not already exist?
The basic way to create the file would be calling the File#createNewFile method:
File counterFile = new File("countervalue.txt");
try {
counterFile.createNewFile();
} catch (Exception e) {
System.out.println("File couldn't been created.");
}
Now, if you want to create a new File and fill it with data, you can use a FileWriter and a PrintWriter for text files (assuming this for the txt extension in your sample):
File counterFile = new File("countervalue.txt");
PrintWriter pw = null;
try {
//it will automatically create the file
pw = new PrintWriter(new FileWriter(counterFile));
pw.println("Hello world!");
} catch (Exception e) {
System.out.println("File couldn't been created.");
} finally {
if (pw != null) {
pw.flush();
pw.close();
}
}
If you want to just append data to your file, use the FileWriter(File, boolean) constructor passing true as the second parameter:
pw = new PrintWriter(new FileWriter(counterFile, true));
Easily done in java
File counterFile = new File("countervalue.txt");
counterFile.createNewFile();
Related
Im using this code in order to write some text to a file, while limiting the size of the file to 1G
but every time a new text is entered, its overriding the current file content.
How do I disable the overriding and still keeping the file size limit?
public synchronized void writeToAFile(String msg,String filePath) {
Path path = FileSystems.getDefault().getPath(filePath);
final long SIZE_1GB = 1073741824L;
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new LimitedOutputStream(Files.newOutputStream(path), SIZE_1GB), StandardCharsets.UTF_8))) {
writer.append(msg);
} catch (Exception e) {
LOGGER.error("Something went wrong while writing to the file {} ", e.getMessage());
e.printStackTrace();
}
}
You should create appendable stream when defining Files.newOutputStream(path).
So providing StandardOpenOption.APPEND option will be fix your problem
// append to an existing file, fail if the file does not exist
// out = Files.newOutputStream(path, APPEND);
Files.newOutputStream(path, StandardOpenOption.APPEND)
To keep the file at the same size, you need to calculate how much room left in the file and open LimitedOutputStream accordingly.
public synchronized void writeToAFile(String msg, String filePath) {
Path path = FileSystems.getDefault().getPath(filePath);
final long fileLength = path.toFile().length();
final long SIZE_1GB = 1073741824L;
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new LimitedOutputStream(Files.newOutputStream(path, StandardOpenOption.APPEND), SIZE_1GB - fileLength), StandardCharsets.UTF_8))) {
writer.append(msg);
} catch (Exception e) {
LOGGER.error("Something went wrong while writing to the file {} ", e.getMessage());
e.printStackTrace();
}
}
Hello this is my code eclipse is telling me the hire ArrayList needs to be an int and I want to print the toString() method in hire class so I can print everything in the array
public static void save() {
try {
File file = new File("D:/Assignment/filename.txt");
// If file does not exists then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for(Hire hire:HireList)
bw.write(hire);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to write the hire.toString(), simply use this :
bw.write(hire.toStrig());
else Javac can't know if your calling bw.write(int)or bw.write(String) or other ...
How do I use FileWriter to actually write into a file and then open it on notepad and see what I wrote? This is what I tried so far:
package Experimental;
import java.io.*;
public class IO {
public static void main (String args[]) {
File f = new File("testFile.txt");
//Outputting into a file
try {
PrintWriter filePrint = new PrintWriter(
new BufferedWriter(new FileWriter(f,true))
);
filePrint.println("testing, testing, printing into a file (apparently)");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Don't forget to close your FileWriter once you are done writing to it.
You should flush and close the PrintWriter like this:
File file = new File("testFile.txt");
PrintWriter filePrint = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
try
{
try
{
filePrint.println("testing, testing, printing into a file (apparently)");
filePrint.flush();
}
finally
{
filePrint.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
I have a java application that needs to write a lot of data into individual lines in a text file. I wrote the code below to do this, but for some reason, it is not writing anything to the text file. It does create the text file, but the text file remains empty after the program is done running. Can anyone show me how to fix the code below so that it actually fills the output file with as many lines of output as it is called upon to do?
public class MyMainClass{
PrintWriter output;
MyMainClass(){
try {output = new PrintWriter("somefile.txt");}
catch (FileNotFoundException e1) {e1.printStackTrace();}
anotherMethod();
}
void anotherMethod(){
output.println("print some variables");
MyOtherClass other = new MyOtherClass();
other.someMethod(this);
}
}
public class MyOtherClass(){
void someMethod(MyMainClass mmc){
mmc.output.println("print some other variables")
}
}
How you are going about doing this seems very strange to me. Why don't you write one method that takes in a string and then writes it to your file? Something like this should work fine
public static void writeToLog(String inString)
{
File f = new File("yourFile.txt");
boolean existsFlag = f.exists();
if(!existsFlag)
{
try {
f.createNewFile();
} catch (IOException e) {
System.out.println("could not create new log file");
e.printStackTrace();
}
}
FileWriter fstream;
try {
fstream = new FileWriter(f, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(inString+"\n");
out.newLine();
out.close();
} catch (IOException e) {
System.out.println("could not write to the file");
e.printStackTrace();
}
return;
}
Use the other constructor:
output = new PrintWriter(new FileWriter("somefile.txt"), true);
According to JavaDoc:
public PrintWriter(Writer out, boolean autoFlush)
Creates a new PrintWriter.
Parameters:
out - A character-output stream
autoFlush - A boolean; if true, the println, printf, or format methods will flush the output buffer
Use other constructor new PrintWriter(new PrintWriter("fileName"), true) for auto-flushing data or
Use flush() and close() when you're done writing
I need to delete the contents of a file, before I write more information into it. I've tried different ways, such as where I delete the content but the file stays the same size, and when I start writing in it after the deletion, a blank hole appears to be the size of the deletion before my new data is written.
This is what I've tried...
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter(path));
bw.write("");
bw.close();
}
catch (IOException e) {
e.printStackTrace();
}
And I've also tried this...
File f = new File(file);
FileWriter fw;
try {
fw = new FileWriter(f,false);
fw.write("");
}
catch (IOException e) {
e.printStackTrace();
}
Can someone please help me with a solution to this problem.
FileWriter (path, false)
The false will tell the writer to truncate the file instead of appending to it.
Try calling flush() before calling close().
FileWriter writer = null;
try {
writer = ... // initialize a writer
writer.write("");
writer.flush(); // flush the stream
} catch (IOException e) {
// do something with exception
} finally {
if (writer != null) {
writer.close();
}
}
It might be because you are not closing the FileWriter, fw.close(); also you dont need to "delete" the old data, just start writing and it will overwrite the old data. So make sure you are closing everywhere.
This works for me:
File f=new File(file);
FileWriter fw;
try {
fw = new FileWriter(f);
fw.write("");
fw.close();
} catch (IOException e) {
e.printStackTrace();
}