Java Saving ArrayList error - java

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 ...

Related

FileWriter writing into file

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();
}

using PrintWriter to write strings to log file

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

list all subfolders in a directory and written on to a text file

I need to list all subfolders in a directory and written on to text file.But when i coded only the last subfolder is only written on to the file.Please help.I am a beginner to Java.
public class Main {
// private Object bufferedWriter;
/**
* Prints some data to a file using a BufferedWriter
*/
public void writeToFile(String filename) {
try
{
BufferedWriter bufferedWriter = null;
bufferedWriter = new BufferedWriter(new FileWriter(filename));
int i=1;
File f=new File("D:/Moviezzz");
File[] fi=f.listFiles();
for(File fil:fi)
{
if(fil.isHidden())
{
System.out.print("");
}
else if(fil.isDirectory()||fil.isFile())
{
int s=i++;
String files = fil.getName();
//Start writing to the output stream
bufferedWriter.write(s+" "+fil);
bufferedWriter.newLine();
// bufferedWriter.write(s+" "+files);
}
}
//Construct the BufferedWriter object
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}catch (IOException ex) {
ex.printStackTrace();}
}
public static void main(String[] args) {
new Main().writeToFile("d://my.txt");
}
}
Uptil you call flush() method of BufferWriter class it will not write your data to file.
It is not necessary to flush() every time in a loop. But you can write it after your end of the loop.
Main thing to put that yourObj.flush() is to keep your buffer memory clean. as after call of that flush() method, data will be release from memory and written to your file.
Close the BufferedReader after the loop.
for(File fil:fi)
{
...
}
bufferedReader.close();
Also, I suggest these changes in your code to make it more readable and efficient:
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filename));
...
if(!fil.isHidden() && (fil.isDirectory() || fil.isFile()))
{
...
}
You can create the BufferedReaderdirectly. Then, you are getting the file name, but not doing anything with it, so just remove the get. And last, you don't have to have put System.out.print(""); in an if to check if the file is hidden. You can use an empty statement or even no code, or use the ! operator to invert.
if(fil.isHidden())
{
; // Do nothing
}
else
{
// Do something
}
if(fil.isHidden()); // Do nothing
else
{
// Do something
}
if(!fil.isHidden)
{
// Do something
}

Create a File if it is not already there

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();

Deleting file contents android

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();
}

Categories