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();
}
Related
How to write a constructor that holds the sorted array, Then write it to a file with a method like getDatabase that returns an object that has been passed the sorted array.
Database class:
public Person[] entry; // this needs to be an array that will hold the person obj each new entry to the array is added to the next avail pos in list
public Database(int capacity) {
entry = new Person[capacity];
size = 0;
}
public Person[] getDatabase() {
return entry;
}
Storage Class:
public dataBase writeCommaSeparated(Database data) throws IOException {
Database db = new Database();
PrintStream writer = new PrintStream(file);
if(file.exists()) {
for(int i = 0; i < data.size; i++) {
writer.println(data.get(i).toFile());
}
}
writer.close();
return db;
}
public dataBase read() throws IOException {
Database db = new Database();
Scanner scan = new Scanner(file);
Person person;
//check if file has data print selected data
while(scan.hasNextLine()) {
person = parsePerson(scan.nextLine());
db.add(person);
}
scan.close();
return db;
}
These are just snippets of the code that I have. I am trying to write a sorted array into a file, and I know that it is sorting the file by age correctly but I am not sure how to write it out to a file.
in main I have:
String fileLocation = File.separator + "Users"
+ File.separator + "USERNAME"
+ File.separator + "Desktop"
+ File.separator + "DataFile.txt";
FileStorage fileStore = new FileStorage(fileLocation);
FileData data = fileStore.read(); // this invokes a method called read that reads the file
data.sort(); // sorts the file by age and prints out to the console the sorted age
fileSort.writeCommaSeparated(data); // writes to the file in a commaseparated way
Focusing on just the sorting of a csv file based on age and given your description, this was about the simplest solution that came to mind.
public class PersonDatabase {
private ArrayList<String[]> people = new ArrayList();
// Reads the given input file and loads it into an ArrayList of string arrays.
public PersonDatabase(String inputFile) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(inputFile));
for (String line = null; null != (line=in.readLine()); ) {
people.add(line.split(",")); // convert csv string to an array of strings.
}
in.close();
}
private static final int AGE_COLUMN_INDEX=2; // Identifies the 'age' column
// performs a numeric comparison on the 'age' column values.
int compareAge(String[] a1, String[]a2) {
return Integer.compare(
Integer.parseInt(a1[AGE_COLUMN_INDEX]),
Integer.parseInt(a2[AGE_COLUMN_INDEX]));
}
// Sorts the list of people by age and writes to the given output file.
public void writeSorted(String outputFile) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter(outputFile));
people.stream()
.sorted(this::compareAge) // sort by age
.forEach(a->{
Arrays.stream(a).forEach(s->out.print(s+",")); // print as csv
out.println();
});
out.close();
}
public static void main(String[] args) throws IOException {
PersonDatabase pdb = new PersonDatabase("persondb.in");
pdb.writeSorted("persondb.out");
}
}
Given the following input:
fred,flintstone,43,
barney,rubble,42,
wilma,flintstone,39,
betty,rubble,39,
This program produces the following output:
wilma,flintstone,39,
betty,rubble,39,
barney,rubble,42,
fred,flintstone,43,
It seemed like marshalling these arrays into Person objects just for the sake of sorting was overkill. However, if you wanted to do that, it would be pretty easy to turn an array of field values into a Person object. I'll leave that to you.
I have an ArrayList of Objects and i want to store them into the file and also i want to read them from the file to ArrayList. I can successfully write them into the file using writeObject method but when reading from the file to ArrayList, i can only read first object. Here is my code for reading from serialized file
public void loadFromFile() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
myStudentList = (ArrayList<Student>) ois.readObject();
}
EDIT:
This is the code for writing list into the file.
public void saveToFile(ArrayList<Student> list) throws IOException {
ObjectOutputStream out = null;
if (!file.exists ()) out = new ObjectOutputStream (new FileOutputStream (file));
else out = new AppendableObjectOutputStream (new FileOutputStream (file, true));
out.writeObject(list);
}
Rest of my class is
public class Student implements Serializable {
String name;
String surname;
int ID;
public ArrayList<Student> myStudentList = new ArrayList<Student>();
File file = new File("src/files/students.txt");
public Student(String namex, String surnamex, int IDx) {
this.name = namex;
this.surname = surnamex;
this.ID = IDx;
}
public Student(){}
//Getters and Setters
public void add() {
Scanner input = new Scanner(System.in);
System.out.println("name");
String name = input.nextLine();
System.out.println("surname");
String surname = input.nextLine();
System.out.println("ID");
int ID = input.nextInt();
Ogrenci studenttemp = new Ogrenci(name, surname, ID);
myOgrenciList.add(studenttemp);
try {
saveToFile(myOgrenciList, true);
}
catch (IOException e){
e.printStackTrace();
}
}
Ok so you are storing whole list of students every time when new student comes in, so basicly what your file is keeping is:
List with one student
List with two students including the first one
List of 3 studens
and so on and so on.
I know you are probably thought it will write only new students in incremental fashion, but you were wrong here
.
You should rather add all students you want to store, into the list first. And then store complete list into the file , just like you are doing it.
Now, when you will be reading from the filre, first readObject will return you the list no.1 - that is why you are getting list with only one student. Second read would give you list no.2 and so on.
So you save your data you either have to:
Create complete list containig N students and store it once ito the file
Do not use list, but store students directly to the file
To read it back:
readObject once, so you will get List<Students>
Read students one by one from the file by multiple calls to readObject
This is Because I think ObjectOutputStream will return the first object from a file.
If you want all of the objects you can use for loop and use like this -:
FileInputStream fis = new FileInputStream("OutObject.txt");
for(int i=0;i<3;i++) {
ObjectInputStream ois = new ObjectInputStream(fis);
Employee emp2 = (Employee) ois.readObject();
System.out.println("Name: " + emp2.getName());
System.out.println("D.O.B.: " + emp2.getSirName());
System.out.println("Department: " + emp2.getId());
}
So I have troubles with creating Json file correctly.
What I have:
1. Gson libs
2. Trying to write in a Json a new user like this:
public static void writeUserBD(String name, String surname, int age) {
//writing in a Json format
JSONObject writeOne = new JSONObject();
JSONArray arr = new JSONArray();
for(int i = 0; i< arr.size() ; i++)
{
writeOne.put("name", name);
writeOne.put("surname", surname);
writeOne.put("age", new Integer(age));
arr.add(writeOne);
writeOne = new JSONObject();
}
//creating dir&file and writing in it
try {
File dir = new File("Test");
dir.mkdir();
File f = new File("Test/TestUser.json");
if (!dir.exists()) {
dir.mkdirs();
} else if (!f.exists()) {
f.createNewFile();
}
//here comes writing encoding problem ! ! !
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f.getAbsoluteFile(), true), Charset.forName("UTF-8")));
try {
bw.write(arr + " " + "\n");
} finally {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
But if I reload my app and try to write a new one it will write a new JSONObject and my output be like :
[{}]
[{}]
In this case i cant parse my json file (for creating simple login) im getting error like "unexcpected token [[]" As I understood this happens becouse of more than 1 jsonobject in a file.
So my question is: how can I write new users data in a json file (even if app was reloaded) in right format that i can pasre than/ for example [{},{},{}]
Try
new FileOutputStream(f.getAbsoluteFile(), false)
true parameter appends to the current file, false should create a new one
The output of your code should be an empty array because you never add an element to the array.
You create a new array and iterate over it. But a new array has no elements and thus the code inside the
loop will never be executed. Beside of that you want to add a new user only once and hence you don't need a loop.
You should read the file first, then add the new user to it and write it back. I created a simple example for you.
I didn't use GSON before, so I'm sure that there is a better way to do this, but it works nevertheless.
I used the try-with-resource feature and the new IO API of Java 7 and did not handle exceptions further. So if you want to handle exceptions
inside the method change the code accordingly. I didn't create the file-structure, so you should do this on your own as well.
public static void writeUserBD(final String name, final String surname, final int age) throws IOException {
final Path jsonFile = Paths.get("Test/TestUser.json");
final JsonArray users = new JsonArray();
// Read all existing users
if (Files.isRegularFile(jsonFile)) {
try (final JsonReader r = new JsonReader(Files.newBufferedReader(jsonFile))) {
r.beginArray();
while (r.hasNext()) {
final JsonObject user = new JsonObject();
r.beginObject();
r.nextName();
user.addProperty("name", r.nextString());
r.nextName();
user.addProperty("surname", r.nextString());
r.nextName();
user.addProperty("age", r.nextInt());
r.endObject();
users.add(user);
}
r.endArray();
}
}
// Create the new user
final JsonObject user = new JsonObject();
user.addProperty("name", name);
user.addProperty("surname", surname);
user.addProperty("age", age);
users.add(user);
// Write all users
try (final BufferedWriter w =
Files.newBufferedWriter(jsonFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
w.write(users.toString());
}
}
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
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.