I am still working on this same program. I though I was almost done after a suggestion in another thread that I implement a try/catch statement which worked well, however I am now getting a "Exception in thread "main" java.lang.NullPointerException at SimpleJavaAssignment.Company.main(Company.java:31)"
Code that triggers the exception:
File file = new File(Company.class.getResource("input.txt").getFile());
Complete code:
package SimpleJavaAssignment;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Company
{
ArrayList<Department> deptList = new ArrayList<Department>();
public Department checkDepartment(String name)
{
for(Department dept: deptList)
{
if(dept.getName().equals(name))
{
return dept;
}
}
Department d = new Department(name);
deptList.add(d);
return d;
}
public static void main(String[] args)
{
System.out.println ("This program will compile and display the stored employee data.");
Scanner inputFile = null;
File file = new File(Company.class.getResource("input.txt").getFile());
try {
inputFile = new Scanner(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Company c = new Company();
String input = inputFile.nextLine();
while(inputFile.hasNextLine() && input.length() != 0)
{
String[] inputArray = input.split(" ");
Department d = c.checkDepartment(inputArray[3]);
d.newEmployee(Integer.parseInt(inputArray[2]), inputArray[0] + " " + inputArray[1], d);
input = inputFile.nextLine();
}
System.out.printf("%-15s %-15s %-15s %-15s %n", "DEPARTMENT", "EMPLOYEE NAME", "EMPLOYEE AGE",
"IS THE AGE A PRIME");
for(Department dept:c.deptList)
{
ArrayList<Employee> empList = dept.getEmployees();
for(Employee emp: empList)
{
emp.printInfo();
}
}
}
}
When you invoke Company.class.getResource("input.txt")
You are using the relative resource name, which is treated relative to the class's package. So, are you sure there is a file called input.txt at the same level of package SimpleJavaAssignment?
You could alternatively just specify the absolute path of the file and pass that into the File constructor, as such:
File file = new File("/my/path/input.txt");
Related
Clarification: I have a text file with multiple lines and I want to separate specific lines into fields for an object.
I have been banging my head against a wall for about 3 days now, and I feel as if I'm overthinking this.
import java.io.*;
import java.util.*;
public class ReadFile {
public static void main(String[] args) throws FileNotFoundException {
String fileName = null;
Scanner input = new Scanner(System.in);
System.out.print("Enter file path: ");
fileName = input.nextLine();
input.close();
String fileText = readFile(fileName);
System.out.println(fileText);
}
public static String readFile(String fileName) throws FileNotFoundException {
String fileText = "";
String lineText = "";
File newFile = new File(fileName);
if (newFile.canRead()) {
try (Scanner scanFile = new Scanner(newFile)) {
while (scanFile.hasNext()) {
lineText = scanFile.nextLine();
if (lineText.startsWith("+")) {
}
else {
fileText = fileText + lineText + "\n";
}
}
} catch (Exception e) {
System.out.println(e);
}
} else {
System.out.println("No file found. Please try again.");
}
return fileText;
}
}
My goal is to take a file that looks similar to this (this is the whole file, imagine a .txt with exactly this in it):
Name of Person
----
Clothing:
Graphic TeeShirt
This shirt has a fun logo of
depicting stackoverflow and a horizon.
****
Brown Slacks
These slacks reach to the floor and
barely cover the ankles.
****
Worn Sandals
The straps on the sandals are frayed,
and the soles are obviously worn.
----
Then I need to extract the top line (e.g.: "Graphic TeeShirt") as a type of clothing the object is wearing, then "This shirt has a fun [...]" as the description of that object.
I have another .java with setters/getters/constructors, but I can't figure out how to iterate through the text file.
Edit: I know I loop through each line, but I need to create an object that has the person's name as a field, the item name (Graphic TeeShirt) as a field, then the description under the item as the next field. Then the next object will be a new object with person's name as a field, the next item (Brown Slacks) as a field, then the description as a field.
I don't know how to separate the lines in to the fields I need.
As I mentioned, the data file format is lousy, which is the real source of the problem, but your delimiters can be used to help out a little. You might approach the problem this way. Obviously don't dump your code like I've done into main but this might start you off. You still need to separate the clothing names from their descriptions but you should get the idea from the below. You can then start making a pojo out of the data.
Pass the path to your data file to this app and look out for the metadata debug outputs of 'Name' and 'Item'.
import java.util.Scanner;
import java.nio.file.Paths;
public class PersonParser {
public static void main(String[] args) {
try {
try (Scanner scPeople = new Scanner(Paths.get(args[0]))) {
scPeople.useDelimiter("----+");
int tokenCount = 0;
while (scPeople.hasNext()) {
String token = scPeople.next();
if (tokenCount % 2 == 0) {
System.out.printf("Name: %s", token);
} else {
// Parse clothing
Scanner scClothing = new Scanner(token);
scClothing.useDelimiter("\\*\\*\\*+");
while (scClothing.hasNext()) {
String item = scClothing.next();
System.out.printf("Item: %s", item);
}
}
tokenCount++;
}
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
The following code is according to the details in your question, namely:
The sample file in your question is the entire file.
You want to create instances of objects that have the following three attributes:
Person's name.
Name of an item of clothing.
Description of that item.
Note that rather than ask the user for the name of the file, I simply use a hard-coded file name. Also note that method toString, in the below code, is simply for testing purposes. The code also uses try-with-resources and method references.
public class ReadFile {
private static final String DELIM = "****";
private static final String LAST = "----";
private String name;
private String item;
private String description;
public void setName(String name) {
this.name = name;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public void setDescription(String description) {
this.description = description;
}
public String toString() {
return String.format("%s | %s | %s", name, item, description);
}
public static void main(String[] strings) {
try (FileReader fr = new FileReader("clothing.txt");
BufferedReader br = new BufferedReader(fr)) {
String line = br.readLine();
String name = line;
br.readLine();
br.readLine();
line = br.readLine();
String item = line;
List<ReadFile> list = new ArrayList<>();
ReadFile instance = new ReadFile();
instance.setName(name);
instance.setItem(item);
line = br.readLine();
StringBuilder description = new StringBuilder();
while (line != null && !LAST.equals(line)) {
if (DELIM.equals(line)) {
instance.setDescription(description.toString());
list.add(instance);
instance = new ReadFile();
instance.setName(name);
description.delete(0, description.length());
}
else {
if (instance.getItem() == null) {
instance.setItem(line);
}
else {
description.append(line);
}
}
line = br.readLine();
}
if (description.length() > 0) {
instance.setDescription(description.toString());
list.add(instance);
}
list.forEach(System.out::println);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Running the above code produces the following output:
Name of Person | Graphic TeeShirt | This shirt has a fun logo ofdepicting stackoverflow and a horizon.
Name of Person | Brown Slacks | These slacks reach to the floor andbarely cover the ankles.
Name of Person | Worn Sandals | The straps on the sandals are frayed,and the soles are obviously worn.
It's not clear what you want to achieve and what is your issue exactly. You said that you can't figure out how to iterate through a text file, so let's dive into this fairly straightforward task.
In general, you have a valid, but the overcomplicated method for reading a file. Modern versions of Java provide a lot simpler methods and it's better to use them (only if you're not implementing some test task to understand how everything is working under the hood).
Please see my example below for reading a file line by line using Java NIO and Streams APIs:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter file path: ");
String fileName = input.nextLine();
input.close();
Path path = Paths.get(fileName);
try (Stream<String> lines = Files.lines(path)) {
lines.filter(line -> {
// filter your lines on some predicate
return line.startsWith("+");
});
// do the mapping to your object
} catch (IOException e) {
throw new IllegalArgumentException("Incorrect file path");
}
}
}
This should allow you to filter the lines from your files based on some predicate and later to the mapping to your POJO if you intend to do so.
If you have any other issues besides reading the file and filtering its content, please add clarification to your questions. Preferably, with examples and test data.
I'm working on a homework assignment and have run into an odd "ArrayOutOfBoundsException" error - I know what the error means (essentially I'm trying to reference a location in an array that isn't there) but I'm not sure why it's throwing that error? I'm not sure what I'm missing, but obviously there must be some logic error somewhere that I'm not seeing.
PhoneDirectory.java
import java.util.HashMap;
import java.io.*;
class PhoneDirectory {
private HashMap<String, String> directoryMap;
File directory;
public PhoneDirectory() { //create file for phone-directory
directory = new File("phone-directory.txt");
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public PhoneDirectory(String phoneDirectoryFile) {
directory = new File(phoneDirectoryFile);
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public String Lookup(String personName) {
if(directoryMap.containsKey(personName))
return directoryMap.get(personName);
else
return "This person is not in the directory.";
}
public void AddOrChangeEntry(String name, String phoneNumber) {
//ASK IF "IF-ELSE" CHECK IS NECESSARY
if(directoryMap.containsKey(name))
directoryMap.put(name,phoneNumber); //if name is a key, update listing
else
directoryMap.put(name, phoneNumber); //otherwise - create new entry with name
}
public void DeleteEntry(String name) {
if(directoryMap.containsKey(name))
directoryMap.remove(name);
else
System.out.println("The person you are looking for is not in this directory.");
}
public void Write() {
try(BufferedWriter writeDestination = new BufferedWriter(new FileWriter(directory)))
{
for(String key : directoryMap.keySet())
{
writeDestination.write(key + ", " + directoryMap.get(key) + '\n');
writeDestination.newLine();
}
}
catch(IOException err) {
err.printStackTrace();
}
}
}
Driver.java
public class Driver {
PhoneDirectory list1;
public static void main(String[] args) {
PhoneDirectory list1 = new PhoneDirectory("test.txt");
list1.AddOrChangeEntry("Disney World","123-456-7890");
list1.Write();
}
}
Essentially I'm creating a file called "test.txt" and adding the line "Disney World, 123-456-7890" - what's weird is that the code still works - but it throws me that error anyway, so what's really happening? (For the record, I'm referring to the line(s): directoryMap.put(fileData[0], fileData[1]) - which would be line 14 and 28 respectively.)
I really just need a point in the right direction for this code. I do not understand how to accomplish what it is asking.
Modify the ProductMainApp class so it responds appropriately if the addProduct and deleteProduct mwthod in the ProductTextFile class returns a flase value.
Modify the ProductTextFile class so it writes exceptions to a tex file names errorLog.txt instead of printing them to the console. To do that, add a method named printToLogFile that accepts an IOException as an argument. This method should append two records to the log file: one that indicates the date and time the exception occured and one that contains information about the exception.
Modify the getProducts and saveProducts methods so they call the printToLogFile method when an error occurs.
Here is the PrintTextFile:
import java.util.*;
import java.io.*;
import java.nio.file.*;
public final class ProductTextFile implements ProductDAO
{
private ArrayList<Product> products = null;
private Path productsPath = null;
private File productsFile = null;
private final String FIELD_SEP = "\t";
public ProductTextFile()
{
productsPath = Paths.get("products.txt");
productsFile = productsPath.toFile();
products = this.getProducts();
}
public ArrayList<Product> getProducts()
{
// if the products file has already been read, don't read it again
if (products != null)
return products;
products = new ArrayList<>();
if (Files.exists(productsPath)) // prevent the FileNotFoundException
{
try
{
if (true)
{
// throw new IOException();
}
// open the input stream
BufferedReader in =
new BufferedReader(
new FileReader(productsFile));
// read all products stored in the file
// into the array list
String line = in.readLine();
while(line != null)
{
String[] columns = line.split(FIELD_SEP);
String code = columns[0];
String description = columns[1];
String price = columns[2];
Product p = new Product(
code, description, Double.parseDouble(price));
products.add(p);
line = in.readLine();
}
// close the input stream
in.close();
}
catch(IOException e)
{
//System.out.println(e);
return null;
}
}
return products;
}
public Product getProduct(String code)
{
for (Product p : products)
{
if (p.getCode().equals(code))
return p;
}
return null;
}
public boolean addProduct(Product p)
{
products.add(p);
return this.saveProducts();
}
public boolean deleteProduct(Product p)
{
products.remove(p);
return this.saveProducts();
}
public boolean updateProduct(Product newProduct)
{
// get the old product and remove it
Product oldProduct = this.getProduct(newProduct.getCode());
int i = products.indexOf(oldProduct);
products.remove(i);
// add the updated product
products.add(i, newProduct);
return this.saveProducts();
}
private boolean saveProducts()
{
try
{
// open the output stream
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productsFile)));
// write all products in the array list
// to the file
for (Product p : products)
{
out.print(p.getCode() + FIELD_SEP);
out.print(p.getDescription() + FIELD_SEP);
out.println(p.getPrice());
}
// close the output stream
out.close();
}
catch(IOException e)
{
System.out.println(e);
return false;
}
return true;
}
}
Here is the ProductMainApp:
import java.util.Scanner;
import java.util.ArrayList;
public class ProductMaintApp implements ProductConstants
{
// declare two class variables
private static ProductDAO productDAO = null;
private static Scanner sc = null;
public static void main(String args[])
{
// display a welcome message
System.out.println("Welcome to the Product Maintenance application\n");
// set the class variables
productDAO = DAOFactory.getProductDAO();
sc = new Scanner(System.in);
// display the command menu
displayMenu();
// perform 1 or more actions
String action = "";
while (!action.equalsIgnoreCase("exit"))
{
// get the input from the user
action = Validator.getString(sc,
"Enter a command: ");
System.out.println();
if (action.equalsIgnoreCase("list"))
displayAllProducts();
else if (action.equalsIgnoreCase("add"))
{
addProduct();
}
else if (action.equalsIgnoreCase("del") || action.equalsIgnoreCase("delete"))
deleteProduct();
else if (action.equalsIgnoreCase("help") || action.equalsIgnoreCase("menu"))
displayMenu();
else if (action.equalsIgnoreCase("exit") || action.equalsIgnoreCase("quit"))
System.out.println("Bye.\n");
else
System.out.println("Error! Not a valid command.\n");
}
}
public static void displayMenu()
{
System.out.println("COMMAND MENU");
System.out.println("list - List all products");
System.out.println("add - Add a product");
System.out.println("del - Delete a product");
System.out.println("help - Show this menu");
System.out.println("exit - Exit this application\n");
}
public static void displayAllProducts()
{
System.out.println("PRODUCT LIST");
ArrayList<Product> products = productDAO.getProducts();
Product p = null;
StringBuilder sb = new StringBuilder();
if (productDAO.getProducts().equals(null))
{
System.out.println("Value Null");
System.exit(0);
}
for (int i = 0; i < products.size(); i++)
{
p = products.get(i);
sb.append(StringUtils.padWithSpaces(
p.getCode(), CODE_SIZE + 4));
sb.append(StringUtils.padWithSpaces(
p.getDescription(), DESCRIPTION_SIZE + 4));
sb.append(
p.getFormattedPrice());
sb.append("\n");
}
System.out.println(sb.toString());
}
public static void addProduct()
{
String code = Validator.getString(
sc, "Enter product code: ");
String description = Validator.getLine(
sc, "Enter product description: ");
double price = Validator.getDouble(
sc, "Enter price: ");
Product product = new Product();
product.setCode(code);
product.setDescription(description);
product.setPrice(price);
productDAO.addProduct(product);
System.out.println();
System.out.println(description
+ " has been added.\n");
}
public static void deleteProduct()
{
String code = Validator.getString(sc,
"Enter product code to delete: ");
Product p = productDAO.getProduct(code);
System.out.println();
if (p != null)
{
productDAO.deleteProduct(p);
System.out.println(p.getDescription()
+ " has been deleted.\n");
}
else
{
System.out.println("No product matches that code.\n");
}
}
}
You can use Exception.printStackTrace (stream) where stream is a outputstream to a file.
http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)
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");
}
So I'm making a program that will store the meetings I've had with some kids I'm tutoring. It'll keep tabs on the meeting times, discussions, and how many hours I've done. I know how to write all the methods to do that, but my issue is that the program will only hold that information for the session that the program is open... how would I go about storing this information and accessing it after the program is closed and opened again?
This is some excerpts from a test score keeper program I did in java class that has this same issue...
public class Student {
private String name;
private int test1;
private int test2;
private int test3;
public Student() {
name = "";
test1 = 0;
test2 = 0;
test3 = 0;
}
public Student(String nm, int t1, int t2, int t3){
name = nm;
test1 = t1;
test2 = t2;
test3 = t3;
}
public Student(Student s){
name = s.name;
test1 = s.test1;
test2 = s.test2;
test3 = s.test3;
}
public void setName(String nm){
name = nm;
}
public String getName (){
return name;
}
public void setScore (int i, int score){
if (i == 1) test1 = score;
else if (i == 2) test2 = score;
else test3 = score;
}
public int getScore (int i){
if (i == 1) return test1;
else if (i == 2) return test2;
else return test3;
}
public int getAverage(){
int average;
average = (int) Math.round((test1 + test2 + test3) / 3.0);
return average;
}
public int getHighScore(){
int highScore;
highScore = test1;
if (test2 > highScore) highScore = test2;
if (test3 > highScore) highScore = test3;
return highScore;
}
public String toString(){
String str;
str = "Name: " + name + "\n" + //\n makes a newline
"Test 1: " + test1 + "\n" +
"Test 2: " + test2 + "\n" +
"Test 3: " + test3 + "\n" +
"Average: " + getAverage();
return str;
}
}
If your data is not too big or complicated - something that you could save in a Rolodex in days gone by - you can save it to a file. Add methods to your class that will format the data properly and write it to a given OutputStream or Writer or whatever. And a method that will read it back.
To write to the file, add an option "save" in your program menu, and when it's chosen, open a file, iterate through your data, and call the saving method for each of your object.
To read from the file, add an option "load" in your program menu, and when it's chosen, open a file, and use your method of reading for each object.
The method for reading can be a static method in the class, that will first see if there are any data in the file and if it can read them properly, and only if it did, will create an object and return it (otherwise return null). There are other options, but this is the one that most encapsulates the needs of the object.
There is also an option to serialize and deserialize each object and put it in an object stream.
If the data is complicated, and there are many objects with various relations between them, you should use a database. This will require learning some database design and SQL.
To demonstrate the file reading/writing idea, add to your Student class:
public void save(PrintWriter outfile) {
outfile.format("%s|%d|%d|%d%n", name, test1, test2, test3);
}
This will write a line with the fields separated by "|" (vertical bar). Of course, you'll have to make sure none of the student names has a vertical bar in it. So you'll need to modify your 4-parameter constructor and your setter:
public Student(String nm, int t1, int t2, int t3) {
name = nm.replaceAll("\\|", "");
test1 = t1;
test2 = t2;
test3 = t3;
}
public void setName(String nm) {
name = nm.replaceAll("\\|", "");
}
Now, to read the file, we add a static method:
public static Student load(BufferedReader infile) throws IOException {
String line;
line = infile.readLine();
// Check if we reached end of file
if (line == null) {
return null;
}
// Split the fields by the "|", and check that we have no less than 4
// fields.
String[] fields = line.split("\\|");
if (fields.length < 4) {
return null;
}
// Parse the test scores
int[] tests = new int[3];
for (int i = 0; i < 3; i++) {
try {
tests[i] = Integer.parseInt(fields[i + 1]);
} catch (NumberFormatException e) {
// The field is not a number. Return null as we cannot parse
// this line.
return null;
}
}
// All checks done, data ready, create a new student record and return
// it
return new Student(fields[0], tests[0], tests[1], tests[2]);
}
You can see that this is more complicated, because you need to check that everything is OK at every step. In any case when things are not OK, we return null but of course, you can decide to just display a warning and read the next line. You'll have to return null when there are no more lines, though.
So, assuming we have a List<Student> students, here is how we write it to a file. I just chose "students.txt" but you can specify a full path leading where you want it. Note how I'm making a backup of the old file before I open the new file. If something goes wrong, at least you have the previous version of the file.
File f = new File("students.txt");
if (f.exists()) {
File backup = new File("students.bak");
if ( ! f.renameTo(backup) ) {
System.err.println( "Could not create backup.");
return;
}
f = new File("students.txt");
}
try ( PrintWriter outFile = new PrintWriter(f);) {
for (Student student : students) {
student.save(outFile);
}
} catch (FileNotFoundException e) {
System.err.println("Could not open file for writing.");
return;
}
After you do this, if you look for the file "students.txt", you will see the records you wrote in it.
How about reading it? Assume we have an empty students list (not null!):
try ( BufferedReader inFile = new BufferedReader(new FileReader(f))) {
Student student;
while ( ( student = Student.load(inFile)) != null) {
students.add(student);
}
} catch (FileNotFoundException e) {
System.err.println( "Could not open file for reading.");
return;
} catch (IOException e) {
System.err.println( "An error occured while reading from the file.");
}
Having done this, you can check your students list, and unless there were errors in the file, all your records will be there.
This is a demonstration, of course. You may want to read into some other collection or instead of printing an error and returning do something else. But it should give you the idea.
You could use db4o for persisting your data. Its an object-database with a spimple api to use. You can store java object read or delete them..
Download it here DB4O
And use the snippets of this tutorial (GER):Tutorial in German
Here is an example:
and Code:
package db4o.example;
public class Student {
String name;
public Student(String name) {
this.name = name;
}
#Override
public String toString() {
return "Student Name: " + name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package db4o.example;
import java.util.List;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
public class Main {
public static void main(String[] args) {
ObjectContainer db = Db4oEmbedded.openFile("F:\\studentDB");
saveExample(db);
readAllExample(db);
readExample(db);
deleteAllExample(db);
db.close();
}
private static void deleteAllExample(ObjectContainer db) {
System.out.println("DeleteAllExample Example:");
List<Student> allStudents =readAllExample(db);
for (Student student : allStudents) {
db.delete(student);
}
db.commit();
}
private static List<Student> readAllExample(ObjectContainer db) {
System.out.println("ReadAllExample Example:");
List<Student> allStudents = db.query(Student.class);
System.out.println("Count: " + allStudents.size());
for (Student student : allStudents) {
System.out.println(student);
}
return allStudents;
}
private static void readExample(ObjectContainer db) {
System.out.println("ReadExample Example:");
Student queryStudent = new Student("Max Mustermann");
// Gets all Students named Max Mustermann
List<Student> students = db.queryByExample(queryStudent);
System.out.println("Count: " + students.size());
for (Student student : students) {
System.out.println(student);
}
}
private static void saveExample(ObjectContainer db) {
System.out.println("Save Example:");
Student myStudent = new Student("Max Mustermann");
db.store(myStudent);
db.commit();
}
}