Write to file from a method with variables from Main - java

I have variables that are from my main, and I want to use a private (or public doesn't really matter I am keeping them in the same class) method to write them to a text file. I have accomplished writing them to a file from within the main... I just cant figure out how to call variables from the main into my writeToFile() method. Below is what I have attempted but Im not sure how to incorporate the two.
//This portion is what I had in my main method that wrote the info to a file successfully
//Write to File
String fileName = "order.txt";
try{
PrintWriter writer = new PrintWriter(fileName);
writer.println("Thank you for ordering from Diamond Cards");
writer.println("Name: " + customerName);
writer.println("Returning Customer: " + customerReturn );
writer.println("Phone: " + custNumber);
writer.println("Card Type: " + customerType);
writer.println("Card Color: " + customerColor);
writer.println("Card Coating: " + customerCoat);
writer.println("Item Amount: " + numItems);
writer.println("Total Cost: " + fmt1.format(totalCostMsg));
writer.flush();
writer.close();
JOptionPane.showMessageDialog(null, "Receipt has been printed");
} catch (FileNotFoundException e)
{e.printStackTrace();
System.exit(0) ;
}
}
// This is where I try to create a method to do the file writing.... not sure how to proceed..
public static void writeToFile() {
try{
FileWriter fw = new FileWriter("order.text"); //File name to be created
PrintWriter pw = new PrintWriter (fw); // Prints to the file that was created
//text to be printed to file
// close the writer
pw.close();
// catch errors
} catch (IOException e) {
out.println("Error!");
}
}
I also need to figure out how to make a separate method to read the file back in but I think I can engineer that if I can just figure this part out.

You can pass objects around by adding parameters to your methods. If you need to reference something in another class or method, just add more parameters.
I suggest that you create a Customer object so that you can pass it around as a single entity instead a couple dozen parameters.
You can try something like this:
public class FileWriteExample {
public static void main(String[] args) {
String fileName = "order.txt";
Customer customer; // Customer object...
int itemCount;
float totalCost;
try {
PrintWriter writer = new PrintWriter(fileName);
writeToFile(writer, customer, itemCount, totalCost);
writer.flush();
writer.close();
JOptionPane.showMessageDialog(null, "Receipt has been printed");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
}
public static void writeToFile(PrintWriter writer, Customer customer,
int itemCount, float totalCost) {
Card card = customer.getCard();
try {
writer.println("Thank you for ordering from Diamond Cards");
writer.println("Name: " + customer.getName());
writer.println("Returning Customer: " + customer.getReturn());
writer.println("Phone: " + customer.getPhone());
writer.println("Card Type: " + card.getType());
writer.println("Card Color: " + card.getColor());
writer.println("Card Coating: " + card.getCoating());
writer.println("Item Amount: " + itemCount);
writer.println("Total Cost: " + fmt1.format(totalCost));
} catch (IOException e) {
System.out.println("Error!");
}
}
}

You want to define writeToFile with arguments, and pass them in from main:
// Add additional arguments.
public static void writeToFile(String fileName, String customerName, ...){
FileWriter fw = new FileWriter(fileName);
writer.println("Thank you for ordering from Diamond Cards");
writer.println("Name: " + customerName);
// Use additional arguments.
}
From main:
writeToFile(fileName, customerName, ...);
I agree with Mr. Polywhirl though. It will be cleaner if you create a wrapping object, although I am not so sure you even need getters and setters for this purpose.
// The types are all String because you did not mention the types in your
// question.
class Customer {
public String Name;
public String Return;
public String Number;
public String Type;
public String Color;
public String Coat;
public Customer String(String Name, String Return, String Number, String Type, String Color, String Coat) {
this.Name = Name;
this.Return = Return;
this.Number = Number;
this.Type = Type;
this.Color = Color;
this.Coat = Coat;
}
}
You could then do the following in main:
Customer c = new Customer(customerName, customerReturn, customerNumber, customerType, customerColor, customerCoat);
Inside the writeToFile method with the same signature as Mr. Polywhirl's answer, you could directly do customer.Name, etc.

There might be some fields that are not required or unavailable, like contact number, etc. Rather than sending a long list to write to file, consider using a Builder Pattern as suggested by Joshua Bloch in Effective Java.

Related

How do you get BufferedWriter to remove brackets from an ArrayList when writing to a file?

I have made a bufferedWriter to take an arraylist of things and comma separate them. It works well, but when I retrieve the data it starts adding extra brackets: [banana, potato, tomato, carrot] goes in and [[banana, potato, tomato, carrot]] comes out. This is the code that writes the file:
public static void writeToCSV() throws IOException {//Finds the file name.
BufferedWriter bufferedWriter = null;
try {
String gameHeader = String.valueOf(getTitleRow());
//Finds the file
File file = new File("_GAMES/" + getSaveName() + "_" + stepped + ".csv");
FileWriter fileWriter = new FileWriter(file);
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(gameHeader);
System.out.println("File: " + getSaveName() + " written");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedWriter!=null) {
bufferedWriter.close();
}
} catch (Exception ex) {
System.out.println("Error in closing" + ex);
}
}
}
This is the array list:
ArrayList<String> headerRow = new ArrayList<>();
headerRow.add(strDate);
headerRow.add("6 x 10");
headerRow.add("1");
headerRow.add("6");
headerRow.add("11");
I also use a getter/setter to move the array list between scopes:
private static ArrayList<String> titleRow = new ArrayList<>();
public static ArrayList<String> getTitleRow() {
return titleRow;
}
public void setTitleRow(ArrayList<String> titleRow) {
this.titleRow = new ArrayList<>(titleRow);
}
I'm sure there is a way to use regex to replace "[" and "]" with "" but I'm not sure where to call it.
The problem is that you use String.valueOf(list) as a way to get a comma separated list of values.
That is not good, cause the string representation of a list adds the brakets around its values: [value1, value2, value3, ...].
A better solution is to replace String.valueOf() with
String.join(",", getTitleRow()));
which yields:
2022-04-13,6 x 10,1,6,11
this is not perfect, since sometimes values require to be quoted (surrounded by " "), but it might be enough for your needs.
Alternatively use a csv library like https://commons.apache.org/proper/commons-csv/.

saving data to a file in Java

i am working with a app which is similar to contacts app.Here i want store the data of person in a file.i have little experience with databases.I have no experience with files.So i want to work with files.I have a class
class Person
{
String name;
String mobile_number;
String city;
}
Now when the user enters the data i want to store the data in a file.While retrieving i want to retrieve the data based on name or mobile or city.like i may have list of 5 persons and i want to retrieve the data of the person with particular name.So i want to know the best practices for saving and retrieving the data from a file.
--Thank you
Here is an example:
public class Person implements Serializable {
private static final long serialVersionUID = -3206878715983958638L;
String name;
String mobile_number;
String city;
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person p = new Person();
p.name = "foo";
// Write
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.dat"))){
oos.writeObject(p);
}
// Read
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.dat"))) {
Person person = (Person) ois.readObject();
System.out.println(person.name);
}
}
}
Here is sample code to store retrieved data into the file.
try {
// Assuming the Contact bean list are taken from database and stored in list
List<ContactBean> beanList = database.getContactList();
File file = new File(".../filpath/filename.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (ContactBean contactbean : beanList) {
bw.write("name : " + contactbean.getName() + " , ");
bw.write("mobile Number : " + contactbean.getMobileNo() + " , ");
bw.write("city : " + contactbean.getCity() + " , ");
bw.write("/n");
}
bw.close();
} catch (Exception e) {
e.printStrace();
}

How to search for values then modify the current value from the file if the value was found

So say for example I have this file
I want my program to search for the title and respective author using the input from the user and then ask for replacement values. Then these replacements will change the current value in the file.
This is my current implementation:
import java.io.*;
import javax.swing.*;
public class SecondChild4 extends SecondParent
{
public void edit(String sFileName, String sFileName2)
{
try
{
sFileName2 = "Second.txt";
File nfile2 = new File("Second.txt");
File file2 = new File("TempSecond.txt");
FileReader reader2 = new FileReader(sFileName2);
BufferedReader br2 = new BufferedReader(reader2);
FileWriter twriter2 = new FileWriter(file2);
BufferedWriter tbw2 = new BufferedWriter(twriter2);
String line2 = "";
String edit2 = "";
String btitle = JOptionPane.showInputDialog (null, "Title: ", "");
String bauthor = JOptionPane.showInputDialog (null, "Author: ", "");
//how to search if value was found from the file?
String btitle1 = JOptionPane.showInputDialog (null, "Replace with title: ", "");
String bauthor1 = JOptionPane.showInputDialog (null, "Replace with author: ", "");
line2 = br2.readLine();
while(line2 != null){
if (line2 == null)
{
// End of File
tbw2.close();
br2.close();
}
else if(what condition to put here?)
{
System.out.println("Search found");
edit = line2.replaceAll(btitle, btitle1);
edit2 = line2.replaceAll(bauthor, bauthor1);
tbw1.append(edit);
tbw1.append(",");
tbw1.append(edit2);
tbw1.append("\n");
tbw2.write(edit);
tbw2.write("\t");
tbw2.write(edit2);
tbw2.newLine();
tbw1.close();
tbw2.close();
br1.close();
br2.close();
}
else{
tbw1.append(line1);
tbw1.append("\n");
tbw2.write(line2);
tbw2.newLine();
tbw1.close();
tbw2.close();
br1.close();
br2.close();
}
}
file2.delete();
file2.renameTo(nfile2);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
I made a temp file for the storage of the modified values and then delete the old file and rename the temp file according to the previous file's name. In the code I made, there are problems such as the file contents get empty(I am also saving it in csv but did not put the codes related to that here. When it comes to csv, only the first line of the previous file gets rewritten to the temp), the file don't get deleted and renamed.
I know there are lots of mistakes with my code. I'm pretty new to programming. Please help me :)
You can do it nicely by creating a book.properties file like
Title=Foo
Author=bar
Java code will be like :
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class SecondChild4 {
private InputStream inputStream;
public static void main(String[] args) {
SecondChild4 s = new SecondChild4();
s.getPropValues();
}
public String getPropValues() {
String result = "";
try {
Properties prop = new Properties();
String propFileName = "book.properties";
inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
// get the property value and print it out
String title = prop.getProperty("Title");
String author = prop.getProperty("Author");
result = "Book = " + author + " title " + title;
System.out.println("current book details are " + result);
// replace logic here
prop.setProperty("Title", "Hamlet");
prop.setProperty("Author", "William Shakespeare");
System.out.println("after modification");
result = "Book = " + prop.getProperty("Author") + " title " + prop.getProperty("Title");
System.out.println("cuurrent book details are " + result);
} catch (Exception e) {
System.out.println("Exception: " + e);
} finally {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
}
Output :
current book details are Book = bar title Foo after modification
current book details are Book = William Shakespeare title Hamlet
Some things for you to remember while coding :
Dont put everything in try catch block just for sake of avoiding exceptions,keep only part that actually throws that exception...not whole code.
call all close methods eg: buffereader.close() in finally block
Never, never, never throw an exception , instead catch it there itself.

How to write code data into a text file

I just did a simple code which takes user name and phone number and save those into an arraylist by creating object. I want to save those information (name and phonenumber) into a text file so that all old information I can get again. How do I do it? Here is my code ...
import java.util.ArrayList;
import java.util.Scanner;
public class manager {
Scanner input = new Scanner(System.in);
ArrayList <objectclass> Test = new ArrayList <objectclass> ();
public void mainloop() {
for (int i = 0; i < 100; i++) {
String x;
System.out.println("Please Select your option");
System.out.println("............................");
System.out.println("1 ADD NAME AND NUMBER\n2 SEARCH NAME AND NUMBER \n0 EXIT");
System.out.println("............................");
x = input.nextLine();
if (x.equalsIgnoreCase("0")) {
System.out.println("Thank you!");
break;
}
if (x.equalsIgnoreCase("1")) {
String Name;
String Number;
System.out.println("Please Enter your Name below");
Name = input.nextLine();
System.out.println("Please Enter your Number below");
Number = input.nextLine();
objectclass objectclassObject = new objectclass(Name, Number);
Test.add(objectclassObject);
}
if (x.equalsIgnoreCase("2")) {
String y;
System.out.println("*** Enter your Name below for search ***");
y = input.nextLine();
for (objectclass p : Test) {
String z = p.getName();
if (z.equalsIgnoreCase(y)) {
System.out.println("Your Name is: " + p.getName() + "\nYour Number is: " + p.getNumber());
System.out.println("");
} else {
System.out.println("Contact not Found!\n");
}
}
}
}
}
}
I want to save all name and number that I store in arraylist into a text file ... how can I do it?
I tried this so far but don't know what to do next ...
import java.io.;
import java.lang.;
import java.util.*;
public class creatfile {
private Formatter x;
public void openFile(){
try{
x = new Formatter("testkyo");
}catch (Exception e){
System.out.println("you have an error");
}
}
public void addRecord(){
x.format();
}
public void closeFile(){
x.close();
}
You need to serialize an object in order to save it onto the file .
here's a tutorial on how to do it, its really simple.
When you serialize an object you can write it onto a file and then load it as it is from there .
EDIT :
example on how you could use this here , i guess the ObjectClass is the thing u want to save so :
class ObjectClass implements Serializable {
String name;
String number;
//constructor , setters , getters and w.e functions .
public static void main (String args[]){
try{
ObjectClass test = new ObjectClass("test",2);
File f = new File("path to file");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(test); // this will write the object as it is onto the file
out.close();
}catch(Exception ex){}
}
}
you wont be able to read the data cuz its serialised , but u can load them as objects like so :
ObjectInputStream in = new ObjectInputStream(new File("path to file"));
ObjectClass test =(ObjectClass) in.readObject(); // u have to cast from Object to Objectclass
what you propably want is an ObjectOutputstream writing your ArrayList to a file via an FileOutputStream when the porgram is exiting and reading the Arraylist with the coresponding InputStreams. See the links below:
http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html
http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html
A simple example:
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("./output.txt"));
writer.write("Hello World");
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
This will write "Hello World" in the text file named: "output.txt".
Check the java I/O api.
You can find a lot of tutorials on the web about this, like:
Reading, Writing, and Creating Files
Creating, Writing, Reading files using Java Files API of Java 7

Java writeout program Unhandled exception type IOException

I'm getting multiple erros with this part of my program. What it basically does is read input from an unorganized file, PersonnelInfo.txt, and it sorts it into an array in the EmployeeInfo class (not posted because I don't believe the problem lies in that class, if you guys want, I will post it for reference).
After sorting the info (Like Name, ID number, title at the company, etc.) the program writes this to another file, ORGANIZEDPersonnelInfo.txt, which will be sorted as such:
Name: Employee name here
ID: Employee ID here
etc.
One error I am getting is in the "static FileWriter writeOut..." line and it is "Unhandled exception type IOException. I put a throws IOException in the main method declaration but it did nothing.
Next, in the "public String toString()" method I am receiving multiple errors. When I try to make it void, it says the return type is incompatible with Object.toString(). When I keep it as a String and return null it wants me to use try/catch but the main error still exists.
Please help! This is getting pretty frustrating...
import java.io.*;
import java.util.Scanner;
public class HR {
static EmployeeInfo[] employee = new EmployeeInfo[4];
static FileWriter writeOut = new FileWriter("/Users/zach/Documents/workspace/Dec. 10, 2012/src/ORAGNIZEDPersonnelInfo.txt");
static BufferedWriter out = new BufferedWriter(writeOut);
public static void main(String[] args) throws IOException {
File PersonnelInfo = new File("/Users/zach/Documents/workspace/Dec. 10, 2012/src/PersonnelInfo.txt");
Scanner inputFile = new Scanner(PersonnelInfo);
int numOfEmployees = Integer.parseInt(inputFile.nextLine());
System.out.println("Number of employees: " + numOfEmployees);
for (int i = 0; i < 4; i++) {
String name = inputFile.nextLine();
String ID = inputFile.nextLine();
String title= inputFile.nextLine();
String startDate = inputFile.nextLine();
employee[i] = new EmployeeInfo(name, ID, title, startDate);
}
listEmployeeInfo();
employee.toString();
}
public String toString() {
for (EmployeeInfo i: employee) {
out.write("Name: " + i.getName());
out.write("ID: " + i.getID());
out.write("Title: " + i.getTitle());
out.write("Start Date: " + i.getStartDate());
}
return null;
}
If you override toString() (as you're doing, since toSTring() is a method from Object, and you're redefining it in your class, which extends Object as all classes do), you should respect the contract of the overridden method, which is to return a String representation of the object (and not to write fields to a buffered writer. Name this method with another name.
Moreover, you're calling a method (out.write()) which throws a checked exception: IOException. So, either you know how to handle this exception, and you should catch it, or you don't know how to handle it, and the method should declare that it throws the exception:
public void writeToOut() throws IOException {
for (EmployeeInfo i: employee) {
out.write("Name: " + i.getName());
out.write("ID: " + i.getID());
out.write("Title: " + i.getTitle());
out.write("Start Date: " + i.getStartDate());
}
}
You have other compilation errors in your program. Each one comes with an error message, a file name and a line number. Try to understand the message, and to fix the error. Read the Java tutorial about exceptions to understand how to handle them.
If you still can't handle them after having read this tutorial, ask another question and paste the exact error message you get from the compiler.
When you are executing static void main, you are not in an instance of the class HR but rather in a static method of it. So if you want to use the toString() method you've written, you'd have to do new HR().toString()
You would be better off removing the static keyword from all the fields and creating an instance of the HR object, then opening the file in the Constructor of that object, i.e.
public HR() {
try {
this.writeOut = new FileWriter("/Users/zach/Documents/workspace/Dec. 10, 2012/src/ORAGNIZEDPersonnelInfo.txt");
} catch (IOException e) {
// handle it, etc.
}
}
public void processFile() {
// Do the stuff
}
public static void main(String[] args) {
HR myHR = new HR().processFile();
// etc.
}
This would allow you to use the toString() method and allow you to handle the exception the way you want to.
Others have addresses toString(), so I'll have a go at the FileWriter...
I'd populate writeOut in a method rather than static scope so you can catch the exception and even try a different filename or something:
FileWriter openOutputfile(String name)
{
boolean done = false;
FileWriter result = null
try {
result = new FileWriter(...);
done = true;
}
catch(IOException ex) {
// print the stack trace
// prompt for another filename
// name = read line
}
return result;
}
I would advice to move your static declaration of Writer inside your main for two reasons (one they don't need to be a static attributes and also the IOException is being handled there). Get the string from toString and use the writer to write the string in the file:
public class HR {
static EmployeeInfo[] employee = new EmployeeInfo[4];
public static void main(String[] args) throws IOException {
FileWriter writeOut =
new FileWriter("/Users/zach/Documents/workspace/"+
"Dec. 10, 2012/src/ORAGNIZEDPersonnelInfo.txt");
BufferedWriter out = new BufferedWriter(writeOut);
File PersonnelInfo = new File("/Users/zach/Documents/workspace/"+
"Dec. 10, 2012/src/PersonnelInfo.txt");
Scanner inputFile = new Scanner(PersonnelInfo);
....
//write employee string in the file
out.write(getEmployeeString());
out.close();
}
public String getEmployeeString() {
StringBuilder stringBuilder = new StringBuilder();
for (EmployeeInfo i: employee) {
stringBuilder.append("Name: " + i.getName());
stringBuilder.append("ID: " + i.getID());
stringBuilder.append("Title: " + i.getTitle());
stringBuilder.append("Start Date: " + i.getStartDate());
}
return stringBuilder.toString();
}
}
If you must need to make them as static variables then do the initialization in a static block with exception handling as below:
static FileWriter writeOut;
static BufferedWriter out;
static {
try{
writeOut =
new FileWriter("/Users/zach/Documents/workspace/"+
"Dec. 10, 2012/src/ORAGNIZEDPersonnelInfo.txt");
out = new BufferedWriter(writeOut);
}catch(IOException ioex){
ioex.printStackTrace();
}
}
Corrected toString()
public String toString() {
StringBuffer buf = new StringBuffer();
for (EmployeeInfo i: employee) {
buf.append("Name: ").append(i.getName());
buf.append("ID: ").append(i.getID());
// ....
}
return buf.toString();
}
in main you print the content:
HR hr = new HR();
out.write(hr.toString());
But I would write using an own write method "writeEmployees(out)"
see Solution of poster JB Nizet

Categories