Adding Strings to txt file - java

So here's the code
public class HospitalManager {
Writer write = new FileWriter("C:\\Users\\Tigra\\Desktop\\TikDevExp\\Patient.txt");
FileWriter fw = new FileWriter("Patient.txt");
BufferedWriter bw = new BufferedWriter(fw);
public HospitalManager() throws IOException {
}
public Patient registerPatient(Patient p1) {
out.println("=Adding new patient=");
out.println("Please enter the name");
Scanner setter = new Scanner(System.in);
p1.name = setter.nextLine();
out.println("Enter the surname");
p1.surName = setter.nextLine();
out.println("Enter the diagnosys");
p1.diagnose = setter.nextLine();
return p1;
}
public void addPatient(Patient addThisOne, List<String> patientList) {
try {
bw.append(addThisOne.name + ", " + addThisOne.surName + ", " + addThisOne.diagnose);
bw.newLine();
bw.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
its in HospitalManager class. In main code I have an instance for that class, and I use addPatient() on it. The thing is, I need it to add String in Patient.txt file each time I use that method. I need String to be added to new line in file, but instead, it stores only first use of addPatient(), second and further uses of method being simply ignored, can you please tell me what can I do to add new line with String each time addPatient() is used?

After you close a Writer, you can't write to it anymore. So, if you want to write to the same file again, you will have to open it each time
public class HospitalManager {
// The Writer write isn't used in your code
// fw and bw will be declared in addPatient
public HospitalManager() { // No IOExceptions here anymore
}
public Patient registerPatient(Patient p1) {
out.println("=Adding new patient=");
out.println("Please enter the name");
Scanner setter = new Scanner(System.in);
p1.name = setter.nextLine();
out.println("Enter the surname");
p1.surName = setter.nextLine();
out.println("Enter the diagnosys");
p1.diagnose = setter.nextLine();
return p1;
}
public void addPatient(Patient addThisOne, List<String> patientList) {
// Declare variables outside of the block so they can be
// referenced in finally
FileWriter fw;
BufferedWriter bw;
try {
fw = new FileWriter("Patient.txt");
bw = new BufferedWriter(bw);
bw.append(addThisOne.name + ", " + addThisOne.surName + ", " + addThisOne.diagnose);
bw.newLine();
bw.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
Alternatively, you could keep the file open until the main code knows that it won't add any other patients.
public class HospitalManager {
FileWriter fw = new FileWriter("Patient.txt");
BufferedWriter bw = new BufferedWriter(fw);
public HospitalManager() throws IOException {
}
public Patient registerPatient(Patient p1) {
out.println("=Adding new patient=");
out.println("Please enter the name");
Scanner setter = new Scanner(System.in);
p1.name = setter.nextLine();
out.println("Enter the surname");
p1.surName = setter.nextLine();
out.println("Enter the diagnosys");
p1.diagnose = setter.nextLine();
return p1;
}
public void addPatient(Patient addThisOne, List<String> patientList) {
try {
bw.append(addThisOne.name + ", " + addThisOne.surName + ", " + addThisOne.diagnose);
bw.newLine();
// Don't close the file, but write the contents of the buffer
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
// Call this when no more patients are going to be added
public void done() {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

ArrayList and BufferedReader Note Taking Program

I have created a simple program that takes a title and a note which you enter then you have a choice to export the notes to txt file using BufferedWriter however because each note is a object which is stored in a ArrayList when storing them I iterate through a for enhanced loop it keeps duplicating each note as I iterate through all the object.
Note Class
import java.util.*;
public class Notes
{
private String notes;
private String titleOfNotes;
Scanner input = new Scanner(System.in);
public Notes()
{
titleOfNote(input);
takeNotes(input);
}
public void takeNotes(Scanner x)
{
System.out.println("Please Enter Your Note");
notes = x.nextLine();
}
public void titleOfNote(Scanner y)
{
System.out.println("Please Enter Title");
titleOfNotes = y.nextLine();
}
public String toString()
{
return "Title: " + titleOfNotes + "\t" + notes;
}
}
App Class //Does mostof the Work
import java.util.*;
import java.io.*;
public class App
{
private int exit = 0;
private int createANote;
private int displayTheNotes;
private int inputFromUser;
public boolean haveFileBeenWritten = true;
File file = new File("Notes.txt");
Scanner input = new Scanner(System.in);
ArrayList<Notes> arrayOfNotes = new ArrayList<Notes>();
public void makeNoteObject()
{
arrayOfNotes.add(new Notes());
}
public void displayAllTheNote(ArrayList<Notes> n)
{
for(Notes singleObjectOfNote : n)
{
System.out.println(singleObjectOfNote);
}
}
public void programUI(){
while(exit != 1)
{
System.out.println("1. Create A Note");
System.out.println("2. Display The Notes");
System.out.println("3. Exit");
System.out.println("4. Export to text file");
System.out.println("Enter Your Operation");
inputFromUser = input.nextInt();
if(inputFromUser == 1)
{
makeNoteObject();
}
else if(inputFromUser == 2)
{
displayAllTheNote(arrayOfNotes);
}
else if(inputFromUser == 3)
{
System.out.println("Exited");
exit = 1;
}
else if(inputFromUser == 4)
{
makeATxtFileFromNotes(arrayOfNotes);
System.out.println("Textfile created filename: " + file.toString());
}
else
{
System.out.println("You Select A Invalid Command");
}
}
}
public void makeATxtFileFromNotes(ArrayList<Notes> x)
{
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file,haveFileBeenWritten)))
{
//Problem here!
for(Notes singleObjectOfNotes : x)
{
bw.write(singleObjectOfNotes.toString());
bw.newLine();
}
}catch(IOException e)
{
System.out.println("Cant Write File: " + file.toString());
haveFileBeenWritten = false;
}
}
public App()
{
programUI();
}
public static void main(String[]args)
{
App objectOfApp = new App();
}
}
I am new to Java so my code my not be the best!
If your problem is that you only need to see current list's Notes excluding the previous', it's because of this line:
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file,haveFileBeenWritten)))
By default, haveFileBeenWritten is true so based on the FileWriter API it will APPEND on the existing file Notes.txt so if you don't want that, change it to false.
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
EDIT: To access List<> elements, use get().
Example:
int size = myList.size();
for (int i = 0 ; i < size ; i++) {
//...
Notes note = myList.get(i);
//...
}

FileInputStream and OutputStream can't read and write objects into file

DESCRIPTION:
In my program, users are asked to input some values. The values get stored into an ArrayList so that I can print them out. Now the problem with this one is all data is lost once I terminate the program. That's why I have decided to store those arrayList object into file and and read them from there.
PROBLEM/QUESTION:
I have created all the related methods to write and read file. But it seems that no objects are written and read in file.The class I am mainly concerned about is ReadWrite.
Working code:
ReadWrite:
public void writeFile(List<PersonInfo> information) {
try {
FileOutputStream fos = new FileOutputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile4.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(information);
os.flush();
fos.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<PersonInfo> readFile() {
List<PersonInfo> dataFromFile=null;
try {
FileInputStream fis = new FileInputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile4.txt");
ObjectInputStream is = new ObjectInputStream(fis);
dataFromFile=(List<PersonInfo>)is.readObject();
fis.close();
is.close();
//return readFile();
} catch (Exception e) {
e.printStackTrace();
}
return dataFromFile;
}
AboutPerson:
Scanner input = new Scanner(System.in);
List<PersonInfo> info = new ArrayList<PersonInfo>();
List<PersonInfo> info2 = new ArrayList<PersonInfo>();
ReadWrite rw=new ReadWrite();
rw.writeFile(info);
info2=rw.readFile();
while (true) {
System.out.println("\n");
System.out.println("1. Input personal info\n"
+ "2. Print them out\n"
+ "*************"
+ "*************");
option1 = input.nextInt();
input.nextLine();
switch (option1) {
case 1:
PersonInfo personInfo = new PersonInfo();
//take the input
System.out.println("Enter a name: ");
personInfo.setName(input.nextLine());
System.out.println("Give ID: ");
personInfo.setId(input.nextInt());
System.out.println("Input credit: ");
personInfo.setCredit(input.nextDouble());
//addint them up
info.add(personInfo);
break;
case 2:
//display them
System.out.println("");
System.out.println("Name\t\tID\t\tCredit");
for (PersonInfo pInfo : info) {
System.out.println(pInfo);
}
System.out.println("\t\t.............\n"
+ "\t\t.............");
break;
}
}
PersonInfo:
........
........
public PersonInfo() {
this.name = null;
this.id = 0;
this.credit = 0;
}
public void setName(String name) {
this.name = name;
}
.........
.........
package com.collection;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class PersonInfo implements Serializable{
private String name;
private int id;
private double credit;
public PersonInfo(){}
public PersonInfo(String name,int id,int credit)
{
this.name=name;
this.id=id;
this.credit=credit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getCredit() {
return credit;
}
public void setCredit(double credit) {
this.credit = credit;
}
}
class ReadWrite
{
public void writeFile(List<PersonInfo> information){
try {
FileOutputStream fos = new FileOutputStream("/home/mohammad.sadik/TestReadWrite.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(information);
os.flush();
fos.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<PersonInfo> readFile() {
List<PersonInfo> dataFromFile=null;
try {
FileInputStream fis = new FileInputStream("/home/mohammad.sadik/TestReadWrite.txt");
ObjectInputStream is = new ObjectInputStream(fis);
dataFromFile=(List<PersonInfo>)is.readObject();
fis.close();
is.close();
//return readFile();
} catch (Exception e) {
e.printStackTrace();
}
return dataFromFile;
}
}
public class AboutPerson {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<PersonInfo> info = new ArrayList<PersonInfo>();
List<PersonInfo> info2 = new ArrayList<PersonInfo>();
ReadWrite rw=new ReadWrite();
while (true) {
System.out.println("\n");
System.out.println("1. Input personal info\n"
+ "2. Print them out\n"
+ "*************"
+ "*************");
int option1 = input.nextInt();
input.nextLine();
switch (option1) {
case 1:
PersonInfo personInfo = new PersonInfo();
//take the input
System.out.println("Enter a name: ");
personInfo.setName(input.nextLine());
System.out.println("Give ID: ");
personInfo.setId(input.nextInt());
System.out.println("Input credit: ");
personInfo.setCredit(input.nextDouble());
//addint them up
info.add(personInfo);
rw.writeFile(info);
break;
case 2:
//display them
info2=rw.readFile();
System.out.println("");
System.out.println("Name\t\tID\t\tCredit");
for (PersonInfo pinfo : info2) {
System.out.println(pinfo.getName()+"\t\t"+pinfo.getId()+"\t\t"+pinfo.getCredit());
}
System.out.println("\t\t.............\n"
+ "\t\t.............");
break;
}
}
}
}
Please implement serializable interface in PersonInf class.When u going to write object into file then u need to implement serializable interface other wise u will get exception like this:
java.io.NotSerializableException: com.collection.PersonInfo
first PersonInfo should implement SerialiZable,
and i'm not sure but PersonInfo should also have a default constructor

add multiple records in textfile

I want to add multiple records in a textfile. So I wrote the following program. But in this program data is overwrite every time user enters data from command prompt. In file data is overwrite. So How to add multiple records in a text file?
apples3.java
class apples3
{ public static void main(String[] args)
{ ffile g = new ffile();
g.get();
g.openFile();
g.addRecords();
g.closeFile();
}
}
ffile.java
import java.io.*;
import java.lang.*;
import java.util.*;
public class ffile
{ private Formatter x;
Scanner sc = new Scanner(System.in);
int rollno;
String fname, lname;
public void get()
{ System.out.println("Enter rollno: ");
rollno = sc.nextInt();
System.out.println("Enter first name: ");
fname = sc.next();
System.out.println("Enter last name: ");
lname = sc.next();
}
public void openFile()
{ try
{ x = new Formatter("xyz.txt");
}
catch(Exception e)
{ System.out.println("You have an error");
}
}
public void addRecords()
{ x.format("%s %s %s ", rollno, fname, lname);
}
public void closeFile()
{ x.close();
}
}
After adding a record i display it using the following code snippet:
Scanner x;
try
{ x = new Scanner(new File("Keyur.txt"));
while(x.hasNext())
{ String a = x.next();
String b = x.next();
String c = x.next();
String d = x.next();
System.out.printf("%s %s %s %s\n", a, b, c, d);
}
x.close();
}
catch(Exception e)
{ System.out.println("could not find file");
}
the output of the display is as following in cmd:
1 ghi mno
2 xyz abc
3 pqr def
Actually i am running this program in my java frame. so i take all the necessary textbox, label, button. when i enter any name in textbox then that names' particular row i want to delete such as i enter xyz then delete row 2 xyz abc from database txt file.
and i write pqr in textbox and in second textbox aaa then i want to update that record in my txt file.
so if this possible then i want only code snippet then it is also useful for me.
Try opening the stream in append mode:
FileOutputStream fos = new FileOutputStream("xyz.txt", true);
x = new Formatter(fos);
According to Java Doc every time you create a Formatter object it will overwrite the file.You can see it here. Try this:
import java.io.*;
import java.lang.*;
import java.util.*;
public class ffile
{
private File file;
BufferedWriter output;
private Formatter x;
Scanner sc = new Scanner(System.in);
int rollno;
String fname, lname;
public void get()
{ System.out.println("Enter rollno: ");
rollno = sc.nextInt();
System.out.println("Enter first name: ");
fname = sc.next();
System.out.println("Enter last name: ");
lname = sc.next();
}
public void openFile()
{ try
{
x = new Formatter();
file = new File("xyz.txt");
}
catch(Exception e)
{ System.out.println("You have an error");
}
}
public void addRecords()
{
try {
output = new BufferedWriter(new FileWriter(file,true));
output.write(x.format("%s %s %s \n", rollno, fname, lname).toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public void closeFile()
{
x.close();
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try using this
public void openFile() {
try {
// APPEND MODE SET HERE
bw = new BufferedWriter(new FileWriter("xyz.txt", true));
x = new Formatter(bw);
} catch (Exception e) {
System.out.println("You have an error");
}
}
public void addRecords() {
x.format("%s %s %s", rollno, fname, lname);
x.format("%s", "\n");
}

Print arraylist to text file in HUMAN READABLE form

so i can't figure out how to print an arraylist index (the first index so 0) to a text file. Basically, I have a Job class which stores 5 variables
public class Job {
public int teamNo;
public String regNo;
public String gridRef;
public String gridCopy;
public String toString() {
return "Job [teamNo=" + teamNo + ", regNo=" + regNo + ", gridRef="
+ gridRef + "";
}
and then I have an arraylist of type Job:
private static ArrayList<Job> teamNoOne = new ArrayList<Job>();
So the data all gets added fine, prints it out etc but I can't save it to a text file. this is my code, I just get the random hash code of it but I need it in human readable form.
try {
File file = new File("JOBS-DONE-LOG.txt");
FileOutputStream fs = new FileOutputStream(file);
ObjectOutputStream os = new ObjectOutputStream(fs);
System.out.println(teamNoOne.get(0));
os.writeObject(teamNoOne.get(0));
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
Can't figure out how to do it.
writeObject serializes the object in your file, it doesn't write it in textual form (http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html#writeObject(java.lang.Object))
You must do it in another way: for example, you can use the BufferedWriter class and the write method to write the output of your toString() method.
Here is a complete example:
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
public class Job {
public String regNo;
public String gridRef;
public String gridCopy;
public String toString() {
return "Job [teamNo=" + teamNo + ", regNo=" + regNo + ", gridRef="
+ gridRef + "";
}
public static void main(String[] args) throws Exception {
ArrayList<Job> teamNoOne = new ArrayList<Job>();
// fill your array
Job job = new Job();
job.regNo = "123";
// continue to fill the jobs...
teamNoOne.add(job);
BufferedWriter writer = new BufferedWriter(new FileWriter("JOBS-DONE-LOG.txt"));
System.out.println(teamNoOne.get(0));
writer.write(teamNoOne.get(0).toString());
os.close();
}
}
Since you are trying to save an arraylist of type Job, it has to be serialized (Refer this).
public class Job implements java.io.Serializable
{
public int teamNo=0;
public String regNo="default";
public String gridRef="default";
public String gridCopy="default";
public String toString() {
return "Job [teamNo=" + teamNo + ", regNo=" + regNo + ", gridRef="
+ gridRef + "";
}
}
For Saving the file
try
{
FileOutputStream fileOut = new FileOutputStream(path);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(teamNoOne);
out.close();
fileOut.close();
}
catch(IOException i)
{
i.printStackTrace();
}
Thus you can load the arraylist back like
Object o = null;
try
{
FileInputStream fileIn = new FileInputStream(path);
ObjectInputStream in = new ObjectInputStream(fileIn);
o = in.readObject();
in.close();
fileIn.close();
}
catch(IOException i)
{
i.printStackTrace();
}
catch(ClassNotFoundException c)
{
c.printStackTrace();
}
Arraylist<Job> loaded_Job = (ArrayList<Job>) o;
Then print the arraylist
for(int i = 0; i < loaded_Job.size(); i++) {
loaded_Job.get(i).toString();
}
This happens because you didn't parameterize your ArrayList. Use generics when declaring your list:
ArrayList<Job> teamNoOne = new ArrayList<Job>();
Because now, though you have overriden your toString() method, teamNoOne.get(0) uses an Object's toString().

Pass string between two threads in java

I have to search a string in a file and write the matched lines to another file.
I have a thread to read a file and a thread to write a file. I want to send the stringBuffer from read thread to write thread. Please help me to pass this. I amm getting null value passed.
write thread:
class OutputThread extends Thread{
/****************** Writes the line with search string to the output file *************/
Thread runner1,runner;
File Out_File;
public OutputThread() {
}
public OutputThread(Thread runner,File Out_File) {
runner1 = new Thread(this,"writeThread"); // (1) Create a new thread.
this.Out_File=Out_File;
this.runner=runner;
runner1.start(); // (2) Start the thread.
}
public void run()
{
try{
BufferedWriter bufferedWriter=new BufferedWriter(new FileWriter(Out_File,true));
System.out.println("inside write");
synchronized(runner){
System.out.println("inside wait");
runner.wait();
}
System.out.println("outside wait");
// bufferedWriter.write(line.toString());
Buffer Buf = new Buffer();
bufferedWriter.write(Buf.buffers);
System.out.println(Buf.buffers);
bufferedWriter.flush();
}
catch(Exception e){
System.out.println(e);
e.printStackTrace();
}
}
}
Read Thraed:
class FileThread extends Thread{
Thread runner;
File dir;
String search_string,stats;
File Out_File,final_output;
StringBuffer sb = new StringBuffer();
public FileThread() {
}
public FileThread(CountDownLatch latch,String threadName,File dir,String search_string,File Out_File,File final_output,String stats) {
runner = new Thread(this, threadName); // (1) Create a new thread.
this.dir=dir;
this.search_string=search_string;
this.Out_File=Out_File;
this.stats=stats;
this.final_output=final_output;
this.latch=latch;
runner.start(); // (2) Start the thread.
}
public void run()
{
try{
Enumeration entries;
ZipFile zipFile;
String source_file_name = dir.toString();
File Source_file = dir;
String extension;
OutputThread out = new OutputThread(runner,Out_File);
int dotPos = source_file_name.lastIndexOf(".");
extension = source_file_name.substring(dotPos+1);
if(extension.equals("zip"))
{
zipFile = new ZipFile(source_file_name);
entries = zipFile.entries();
while(entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry)entries.nextElement();
if(entry.isDirectory()) {
(new File(entry.getName())).mkdir();
continue;
}
searchString(runner,entry.getName(),new BufferedInputStream(zipFile.getInputStream(entry)),Out_File,final_output,search_string,stats);
}
zipFile.close();
}
else
{
searchString(runner,Source_file.toString(),new BufferedInputStream(new FileInputStream(Source_file)),Out_File,final_output,search_string,stats);
}
}
catch(Exception e){
System.out.println(e);
e.printStackTrace();
}
}
/********* Reads the Input Files and Searches for the String ******************************/
public void searchString(Thread runner,String Source_File,BufferedInputStream in,File output_file,File final_output,String search,String stats)
{
int count = 0;
int countw = 0;
int countl=0;
String s;
String[] str;
String newLine = System.getProperty("line.separator");
try
{
BufferedReader br2 = new BufferedReader(new InputStreamReader(in));
//OutputFile outfile = new OutputFile();
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(output_file,true));
Buffer Buf = new Buffer();
//StringBuffer sb = new StringBuffer();
StringBuffer sb1 = new StringBuffer();
while((s = br2.readLine()) != null )
{
str = s.split(search);
count = str.length-1;
countw += count;
if(s.contains(search)){
countl++;
sb.append(s);
sb.append(newLine);
}
if(countl%100==0)
{ System.out.println("inside count");
Buf.setBuffers(sb.toString());
sb.delete(0,sb.length());
System.out.println("outside notify");
synchronized(runner)
{
runner.notify();
}
//outfile.WriteFile(sb,bufferedWriter);
//sb.delete(0,sb.length());
}
}
}
synchronized(runner)
{
runner.notify();
}
br2.close();
in.close();
if(countw == 0)
{
System.out.println("Input File : "+Source_File );
System.out.println("Word not found");
System.exit(0);
}
else
{
System.out.println("Input File : "+Source_File );
System.out.println("Matched word count : "+countw );
System.out.println("Lines with Search String : "+countl);
System.out.println("Output File : "+output_file.toString());
System.out.println();
}
}
catch(Exception e){
System.out.println(e);
e.printStackTrace();
}
}
}
Here is the approach I would use:
Add a queue to the output thread. Make sure access is synchronized.
Add a method to the output thread (say addWork) that accepts a String and adds it to the output queue.
Let the run method of the output thread continually dequeue Strings and write them to the file.
Let the other thread pass Strings to the output thread by calling addWork(String).
Pass the stringbuffer in as a parameter to both.
Any time you access the stringbuffer, make sure you do it inside a synchronized block
synchronized(myStringBuffer) {
myStringBuffer.append("Awesome text");
}
and
synchronized(myStringBuffer) {
myFileOutput.writeln(myStringBuffer.toString());
}
examples above.

Categories