add multiple records in textfile - java

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

Related

Java program not saving object to HashMap

Either my save_product function in my Repository.java class doesn't save correctly into the map product_repository or, maybe it does save, but I'm not outputting it correctly in my find_product function in my Repository.java class. I think I'm using the correct function to search for the value in the map, .get
I experimented with product_repository.keySet().iterator().forEachRemaining(System.out::println); but that's the first time I ever used that... also please forgive how I insert the keyinto the map product_repository in the create_new_product function in the Controller.java class. I'm new to java ...
Main.java
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
Controller controller = new Controller();
controller.create_new_product();
controller.search_product();
}
}
Product.java
package com.company;
public class Product {
private String product_name;
private String product_brand;
private int product_cost;
private int product_count;
private boolean product_availability;
public Product() {
}
public Product(String product_name, String product_brand,
int product_cost, int product_count, boolean product_availability) {
this.product_name = product_name;
this.product_brand = product_brand;
this.product_cost = product_cost;
this.product_count = product_count;
this.product_availability = product_availability;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_brand() {
return product_brand;
}
public void setProduct_brand(String product_brand) {
this.product_brand = product_brand;
}
public int getProduct_cost() {
return product_cost;
}
public void setProduct_cost(int product_cost) {
this.product_cost = product_cost;
}
public int getProduct_count() {
return product_count;
}
public void setProduct_count(int product_count) {
this.product_count = product_count;
}
public boolean isProduct_availability() {
return product_availability;
}
public void setProduct_availability(boolean product_availability) {
this.product_availability = product_availability;
}
}
Controller.java
package com.company;
import java.util.Scanner;
public class Controller {
private static Long key;
public static void create_new_product(){
Repository repository = new Repository();
//Supplier supplier = new Supplier();
Product product = new Product();
Scanner scanner = new Scanner(System.in);
key = 0L;
System.out.println("*****************************************************************");
System.out.println("********************NEW PRODUCT CREATION PAGE********************");
System.out.println("*****************************************************************");
System.out.println("Enter product name: ");
String name = scanner.nextLine();
product.setProduct_name(name);
System.out.println("Enter product brand: ");
String brand = scanner.nextLine();
product.setProduct_brand(brand);
System.out.println("Enter product cost: ");
int cost = scanner.nextInt();
product.setProduct_cost(cost);
System.out.println("Enter amount of products in stock: ");
int amount = scanner.nextInt();
product.setProduct_count(amount);
key++;
repository.save_product(key, product);
}
public void search_product(){
Repository repository = new Repository();
Product product = new Product();
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("*************************FIND PRODUCT PAGE***********************");
System.out.println("*****************************************************************");
// TO DO: Choices or if/else blocks not executing properly
System.out.println("\nSearch by ID or name?\nPress '1' for ID. Press '2' for name: ");
String choice = scanner.next();
if (choice.equals("1")) {
System.out.println("Enter product id: ");
Long id = scanner.nextLong();
repository.find_product(id);
try{
if (product.getProduct_count() > 0){
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
}
else if (choice.equals("2")) {
System.out.println("Enter product name: ");
String name = scanner.next();
repository.find_product(name);
try{
if (product.getProduct_count() > 0){
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
}
else {
System.out.println("Error. We apologize for the inconvenience.");
}
}
}
Repository.java
package com.company;
import java.util.HashMap;
import java.util.Map;
public class Repository {
private Map<Long, Product> product_repository = new HashMap<Long, Product>();
// TO DO: Implement while loops so program doesn't exit at the first error
public void save_product(Long key, Product newProductMap){
try{
if (product_repository.containsValue(newProductMap)) {
System.out.println("This product is already in the system." +
"\nFor safety reasons, we cannot add the same product twice.");
}
else {
product_repository.put(key, newProductMap);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
public void find_product(Long key){
try {
if (product_repository.containsKey(key)) {
System.out.println(product_repository.get(key));
}
else {
System.out.println("No matches were found for product id: " + key);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
// Overload
public void find_product(String name) {
try {
if (product_repository.containsValue(name)) {
System.out.println(product_repository.get(name));
product_repository.keySet().iterator().forEachRemaining(System.out::println);
}
else {
System.out.println("No matches were found for product name: " + name);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
}
You have to make Repository repository a field of your Controller class. You are currently throwing the repositories away after your methods create_new_product and search_product have executed. Therefore you need to remove the first line of each of these methods.
Another problem is inside your find_product(String name) method where your call product_repository.get(name) but name is a String and the get method expects an ID, i.e. a Long so this call will always return null.
As it was pointed out before the repository has to be made global. However, the entire code is a bit messy. You are searching for a product id but the id is not shown to you. It is like searching for database records but the ids are autogenerated. Good luck with that. So I would suggest to allow this program to enter the id as well. It makes much more sense if you want to search for the id.
Otherwise, if you are interested in only the value, id can be taken out.
Below you can find the modified code that works for all the methods.
//main stays the same
public class Main {
public static void main(String[] args) {
// write your code here
Controller controller = new Controller();
controller.create_new_product();
controller.search_product();
}
}
//controller is a bit changed. Added global repository and improved the search.
import java.util.Collection;
import java.util.Scanner;
public class Controller {
private static Long key;
Repository repository = new Repository();
public void create_new_product() {
Product product = new Product();
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("********************NEW PRODUCT CREATION PAGE********************");
System.out.println("*****************************************************************");
System.out.println("Enter product id: ");
long id = Long.parseLong(scanner.nextLine());
product.setProductId(id);
System.out.println("Enter product name: ");
String name = scanner.nextLine();
product.setProduct_name(name);
System.out.println("Enter product brand: ");
String brand = scanner.nextLine();
product.setProduct_brand(brand);
System.out.println("Enter product cost: ");
int cost = scanner.nextInt();
product.setProduct_cost(cost);
System.out.println("Enter amount of products in stock: ");
int amount = scanner.nextInt();
product.setProduct_count(amount);
repository.save_product(id, product);
}
public void search_product() {
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("*************************FIND PRODUCT PAGE***********************");
System.out.println("*****************************************************************");
// TO DO: Choices or if/else blocks not executing properly
System.out.println("\nSearch by ID or name?\nPress '1' for ID. Press '2' for name: ");
String choice = scanner.next();
if (choice.equals("1")) {
System.out.println("Enter product id: ");
Long id = scanner.nextLong();
Product product = repository.find_product(id);
try {
if (product.getProduct_count() > 0) {
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
} else if (choice.equals("2")) {
System.out.println("Enter product name: ");
String name = scanner.next();
Collection<Product> products = repository.find_products(name);
if (products.size() > 0) {
for (Product product : products) {
System.out.println(product.getProduct_name() + " are in stock!");
}
} else {
System.out.println(" out of stock.");
}
} else {
System.out.println("Error. We apologize for the inconvenience.");
}
}
}
//Added a new field to the Repository so you can also search by key.
import java.util.*;
public class Repository {
private Map<Long, Product> product_repository = new HashMap<Long, Product>();
// TO DO: Implement while loops so program doesn't exit at the first error
public void save_product(Long key, Product newProductMap) {
try {
if (!product_repository.containsKey(key)) {
product_repository.put(key, newProductMap);
} else {
System.out.println("This product is already in the system." +
"\nFor safety reasons, we cannot add the same product twice.");
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
public Product find_product(final Long key) {
try {
if (product_repository.containsKey(key)) {
System.out.println("Found product: " + product_repository.get(key).getProduct_name());
return product_repository.get(key);
} else {
System.out.println("No matches were found for product id: " + key);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
return null;
}
// Overload
public Collection<Product> find_products(final String name) {
Collection<Product> values = new ArrayList<>();
for (Map.Entry<Long, Product> productEntry : product_repository.entrySet()) {
if (productEntry.getValue().getProduct_name().equals(name)) {
System.out.println("matches were found for product name: " + name);
values.add(productEntry.getValue());
}
}
return values;
}
}

Adding Strings to txt file

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

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

Null pointer exception after using try/catch

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

Categories