deleting lines from a file - java

I need to delete certain lines from a file, the file is a list of contacts that I read in from a file into my GUI. When I get to the contact I want to delete, my program should delete the contact from the file. I've tried to do this, but it is not working.
Here is the code I'm currently using:
String temp=txtname.getText();
for (Contact Contact:contacts)
{
if (temp.equals(Contact.getname()));
{
txtname.setText("");
txtsurname.setText("");
txtphone.setText("");
txtmobile.setText("");
txtaddress.setText("");
txtpostcode.setText("");
contacts.remove(Contact);
contacts.remove(Contact);
contacts.remove(Contact);
contacts.remove(Contact);
contacts.remove(Contact);
contacts.remove(Contact);
}
}
My contact class is:
public class Contact {
static void add(String text) {
}
public String name;
public String surname;
public String phone;
public String mobile;
public String address;
public String postcode;
public Contact(){}
public Contact(String name, String surname, String phone,
String mobile, String address, String postcode)
{
this.name = name;
this.surname = surname;
this.phone = phone;
this.mobile = mobile;
this.address = address;
this.postcode = postcode;
}
public String getname()
{
return this.name;
}
public String getsurname()
{
return this.surname;
}
public String getphone()
{
return this.phone;
}
public String getmobile()
{
return this.mobile;
}
public String getaddress()
{
return this.address;
}
public String getpostcode()
{
return this.postcode;
}
public void setname(String name)
{
this.name = name;
}
public void setsurname(String surname)
{
this.surname = surname;
}
public void setphone(String phone)
{
this.phone = phone;
}
public void setmobile(String mobile)
{
this.mobile = mobile;
}
public void setaddress(String address)
{
this.address = address;
}
public void setpostcode(String postcode)
{
this.postcode = postcode;
}
}
I'm guessing it deletes it from the arraylist, but I'm not sure how the program knows what to delete from the file.
Thanks.

Modifying the internal list doesn't change the file. There is no automatic way to synchronize the two. You have to save the array back to the file to update it.

There is no way to delete anything from the middle of the file.
The only way is to rewrite the file every time something should be changed.

you can use a random access file but it seems like an over kill for this task.
the best way to do it is to have the remove function write the whole file back to the disk.

If you have no specific format for the file, then I suggest you to use the default serialization and serialize the contacts list. Like this,
//To serialize
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File("D:/newfile.txt")));
out.writeObject(contacts);
//To deserialize
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File("d:/newFile.txt")));
contacts = (ArrayList<Contact>)in.readObject();
You first have to implement the Serializable interface in your Contact class.
Or if you need more control over the file format use the standard XML classes or JSON libraries.

Files can be rewrited, or appended to. In you case you'll have to rewrite it. There are other ways, but they would be an overkill here.
String temp = txtname.getText();
for (Contact contact : contacts) {
if (temp.equals(contact.getname())) {
contacts.remove(contact);
break;
}
}
Fixed a lot of general problems with your code
public class Contact {
private String name;
private String surname;
private String phone;
private String mobile;
private String address;
private String postcode;
public Contact(String name, String surname, String phone, String mobile, String address, String postcode) {
this.name = name;
this.surname = surname;
this.phone = phone;
this.mobile = mobile;
this.address = address;
this.postcode = postcode;
}
public String getName() {
return this.name;
}
public String getSurname() {
return this.surname;
}
public String getPhone() {
return this.phone;
}
public String getMobile() {
return this.mobile;
}
public String getAddress() {
return this.address;
}
public String getPostcode() {
return this.postcode;
}
}

Related

How to Process Data into a CSV File Along with Other Methods Like Copy and Clone?

In my person class, I'm supposed to have a toCSV() method where I return a string for my fields.
A copy method that accepts a Person p and copies all the data.
A copy method that accepts all individual parameters.
And then finally a clone method that returns a Person with a copy of the data.
I wrote the methods off of what I think it is asking for but I'm still confused overall on what it is looking for.
I feel like my code for each of these methods is very redundant and not what the problem is looking for.
I haven't tackled the clone method cause I think the previous three methods are incorrect.
public class Person {
private String firstName;
private String lastName;
private String address;
private String city;
private String state;
private String zipCode;
public Person (String firstName, String lastName, String address, String city, String state, String zipCode) {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
#Override
public String toString() {
return "FirstName: " + firstName + "\nLastName: " + lastName + "\nAddress: " + address + "\nCity: " + city + "\nState: " + state + "\nZipCode: " + zipCode;
}
public void toCSV() throws FileNotFoundException {
PrintWriter file = new PrintWriter(new File("Customer.csv"));
file.append(this.firstName);
file.append(",");
file.append(this.lastName);
file.append(",");
file.append(this.address);
file.append(",");
file.append(this.city);
file.append(",");
file.append(this.state);
file.append(",");
file.append(this.zipCode);
}
public void copy(Person p) throws FileNotFoundException {
PrintWriter file = new PrintWriter(new File("Customer.csv"));
file.append(p.firstName);
file.append(p.lastName);
file.append(p.address);
file.append(p.city);
file.append(p.state);
file.append(p.zipCode);
}
public void copy(String firstName, String lastName, String address, String city, String state, String zipCode) throws FileNotFoundException {
PrintWriter file = new PrintWriter(new File("Customer.csv"));
file.append(firstName);
file.append(lastName);
file.append(address);
file.append(city);
file.append(state);
file.append(zipCode);
}
To be completely honest I am unsure the exact results.
What I'm understanding is that it should return a file with the input line being firstName,lastName,address,city,state,zipcode, I have yet to run it because there are a lot of other pieces I'm missing.
However, I think my problem is that each of the methods will be creating its own new file and I believe it should all be under the same one Customer.csv.
I know this is pretty vague but I just need some help to see if my code is on the right track or that it completely is redundant and isn't going to work how it's intended to.
public void toCSV( File customerFile) throws FileNotFoundException {
doFileOp(customerFile, new Person (this.firstName, this.lastName, this.address, this.city, this.state, this.zipCode));
}
public void copy(Person p, File customerFile) throws FileNotFoundException {
doFileOp(customerFile, p);
}
public void copy(String firstName, String lastName, String address, String city, String state, String zipCode, File customrFile) throws FileNotFoundException {
doFileOp(customerFile, new Person (firstName, lastName, address, city, state, zipCode));
}
private void doFileOp(File customerFile, Person p) {
PrintWriter file = new PrintWriter(customerFile);
customerFile.append(p.firstName); file.append(",");
customerFile.append(p.lastName); file.append(",");
customerFile.append(p.address); file.append(",");
customerFile.append(p.city); file.append(",");
customerFile.append(p.state); file.append(",");
customerFile.append(p.zipCode); file.append(",");
}

Android Simple Adapter

I am getting this error when I am trying to compile. This used to work when I was using sdk 23 but now that I have upgraded to 26 I cant get it to compile.
Error:(41, 13) error: cannot find symbol class SimpleAdapter
This is my code that goes and gets a list of contacts off a website and displays them in a list view.
public class ContactsActivity extends Activity {
private SimpleAdapter adpt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
adpt = new SimpleAdapter(new ArrayList<Contact>(), this);
adpt.setStyle(R.layout.contact_list_item);
ListView lView = (ListView) findViewById(R.id.listview_contacts);
The contact class is as follows this is what I cast the returned xml into once it gets returned.
public class Contact implements Serializable {
private String Name;
private String Phone;
private String Cell;
private String Email;
private String Address;
private String Work;
public Contact() {
super();
}
public Contact(String name, String phone, String cell, String email, String address,String work) {
super();
this.Name = name;
this.Phone = phone;
this.Cell = cell;
this.Email = email;
this.Address = address;
this.Work = work;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
this.Phone = phone;
}
public String getCell() {
return Cell;
}
public void setCell(String cell) {
this.Cell = cell;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
this.Email = email;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
this.Address = address;
}
public String getWork() {
return Work;
}
public void setWork(String work) {
this.Work = work;
}
}
Please let me know where I am going wrong.
You need create a SimpleAdapter, can extend from ArrayAdapter, BaseAdapter,...

Test file error

I have 2 subclasses and one superclass. I try to run test file but don't work. Any suggest?
Error: https://i.imgur.com/ciG9EPF.png
First file, the superclass (persoana= person)
package proj;
public class persoana {
private String name, address, phone, email;
public persoana(){
}
public persoana(String name, String address, String phone, String email) {
this.name = name;
this.address = address;
this.phone = phone;
this.email = email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address = address;
}
public String getPhone(){
return phone;
}
public void setPhone(String phone){
this.phone = phone;
}
public String getEmail(){
return phone;
}
public void setEmail(String email){
this.email = email;
}
}
File 2 is employee, subclass for persoana:
package proj;
public class employee extends persoana{
private String office, salary;
public employee(){
}
public employee(String office, String salary){
this.office = office;
this.salary = salary;
}
public String office(){
return office;
}
public void setOffice(String office){
this.office = office;
}
public String getSalary(){
return salary;
}
public void setSalary(String salary){
this.salary = salary;
}
}
File 3, subclass of class persoana:
package proj;
public class student extends persoana{
private String bac, adm;
public student(){
}
public student(String bac, String adm){
this.bac = bac;
this.adm = adm;
}
public String bac(){
return bac;
}
public void setBac(String bac){
this.bac = bac;
}
public String getAdm(){
return adm;
}
public void setAdm(String adm){
this.adm = adm;
}
}
And the test file where appears 2 errors at line 6 and 7
package proj;
public class test {
public static void main(String[] args) {
persoana persoana= new persoana ("John", "Somewhere", "415",
"john#somewhere.com");
persoana student= new student("Jane", "School Street", "650", "mj#abc.com");
persoana employee= new employee ("Tom ", "Street", "408", "asd");
System.out.println(persoana.toString() + "\n");
System.out.println(student.toString() + "\n");
System.out.println(employee.toString() + "\n");
}
}
Your student class don't provide that constructor (and constructor are not inherited like methods).
You need to provide it.
public student(String name, String address, String phone, String email){
super(name, adress, phone, email);
}
Note that class shoud start with a uppercase.

Validating response from REST API call

I am working on error handling a response mapping. Before I go ahead and map the response to my domain objects, I want to validate the response. Check for errors.
I am planning to have a Validator.java class and implement validation methods for each of the API call.
Is there any alternative way in spring to do this?
package com.people.net;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
public class UserInfo {
//Unicode check
#Pattern(regexp="[0-9a-zA-Z\\s-]+", message="chars,numbers allowed only")
String name;
int id;
#Pattern(regexp="([0-9]{10})", message="minLength=maxLength=10 only numbers")
String pin;
#Email
String email;
#Size(max=5, message="5 chars max")
String emailType;
#Size(max=5, message="5 chars max")
String addressType;
#Size(max=300, message="5 chars max")
String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UserInfo(String name, String pin, String id) {
super();
this.id = Integer.parseInt(id);
this.name = name;
this.pin = pin;
}
public UserInfo(int id,String name, String pin, String email, String emailType, String addressType, String address) {
super();
this.id = id;
this.name = name;
this.pin = pin;
this.email = email;
this.emailType = emailType;
this.addressType = addressType;
this.address = address;
}
public UserInfo() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmailType() {
return emailType;
}
public void setEmailType(String emailType) {
this.emailType = emailType;
}
public String getAddressType() {
return addressType;
}
public void setAddressType(String addressType) {
this.addressType = addressType;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
You should explore hibernate validator which is the reference implementation JSR-349 for bean validation. more info is here https://jcp.org/en/jsr/detail?id=349 .
Also hibernate validator is a industry standard for doing the bean validation(lots of stuff available on internet) and comes with lots of popular framework like dropwizard etc.it provide annotation based validation and allow you to write your own custom annotation based validation.
please refer on step by step guide http://www.journaldev.com/2668/spring-validation-example-mvc-validator, where author uses it with the spring.

It show the error that Customer is already defined.Please let me know whats wrong and how to correct it

There is a compliation error stating that class name is already define i can't find the way to resolve it
further the class name are declared only once and can't find the place where the things are going wrong
package practo;
import java.io.*;
import java.lang.*;
import java.util.*;
#SuppressWarnings("unused")
class Customer /* compilation error occurs here */
{
private int id;
private String name;
private String email;
private String address;
void setid(int id)
{
this.id=id;
}
int getid()
{
return id;
}
void setname(String name)
{
this.name=name;
}
String getname()
{
return name;
}
void setemail(String email)
{
this.email=email;
}
String getemail()
{
return email;
}
void setaddress(String address)
{
this.address=address;
}
String getaddress()
{
return address;
}
class PhoneNumber
{
private String phoneNumber;
private String heldFromDate;
private String heldToDate;
void setphoneNumber(String phoneNumber)
{
this.phoneNumber=phoneNumber;
}
String getphoneNumber()
{
return phoneNumber;
}
void setheldToDate(String heldToDate)
{
this.heldToDate=heldToDate;
}
String getheldToDate()
{
return heldToDate;
}
public String getHeldFromDate() {
return heldFromDate;
}
public void setHeldFromDate(String heldFromDate) {
this.heldFromDate = heldFromDate;
}
class NumberType
{
private String code;
private String description;
void setcode(String code)
{
this.code=code;
}
void setdescription(String description)
{
this.description=description;
}
String getcode()
{
return code;
}
String getdescription()
{
return description;
}
}
}
}
class x1
{
public void main(String args[])
{
#SuppressWarnings("resource")
Scanner s=new Scanner(System.in);
Customer c=new Customer();
Customer.PhoneNumber p=c.new PhoneNumber();
Customer.PhoneNumber.NumberType n=p.new NumberType();
System.out.println("Enter the customer details");
System.out.println("Enter the id :");
int id=s.nextInt();
c.setid(id);
System.out.println(c.getid());
System.out.println("Enter the name :");
String name=s.nextLine();
c.setname(name);
System.out.println(c.getname());
System.out.println("Enter the email :");
String email=s.nextLine();
c.setemail(email);
System.out.println(c.getemail());
System.out.println("Enter the address :");
String address=s.nextLine();
c.setaddress(address);
System.out.println(c.getaddress());
System.out.println("Enter the customer contact details");
System.out.println("Enter the phone number :");
String phoneNumber=s.nextLine();
p.setphoneNumber(phoneNumber);
System.out.println(p.getphoneNumber());
System.out.println("Enter the held from date (dd/MM/yyyy) :");
String heldFromDate=s.next();
p.setHeldFromDate(heldFromDate);
System.out.println(p.getHeldFromDate());
System.out.println("Enter the held to date (dd/MM/yyyy) :");
String heldToDate=s.next();
p.setheldToDate(heldToDate);
System.out.println(p.getheldToDate());
System.out.println("Enter number type code :");
String code=s.next();
n.setcode(code);
System.out.println(n.getcode());
System.out.println("Enter number type description");
String description=s.next();
n.setdescription(description);
System.out.println(n.getdescription());
}
}
Your class does not give me any compilation error. You might try making the class public i.e. public class Customer and file name having the name Customer.java. It may happen that the package practo already contains a class named Customer.
Can you please verify Customer class is not duplicate ? If it is not there, can you choose Clean from the Project menu, it might fix these errors.
Sometime eclipse trouble us.
Lots of recommendations for improvement:
Open public class per file, and a file for each class. Your arrangement is confusing.
Learn and follow the Java coding standards.
Using a Date for a date instead of a String is a better design, especially with JDK 8 and the java.time package.
Learn JUnit instead of that x1.main.
These are examples of how your classes should look.
Customer.java
package practo;
/**
* Created by Michael
* Creation date 5/29/2016.
* #link https://stackoverflow.com/questions/37511168/it-show-the-error-that-customer-is-already-defined-please-let-me-know-whats-wron
*/
public class Customer {
private int id;
private String name;
private String email;
private String address;
public Customer() {
this(0, "", "", "");
}
public Customer(int id, String name, String email, String address) {
this.id = id;
this.name = name;
this.email = email;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
PhoneNumber.java:
package practo;
/**
* Created by Michael
* Creation date 5/29/2016.
* #link https://stackoverflow.com/questions/37511168/it-show-the-error-that-customer-is-already-defined-please-let-me-know-whats-wron
*/
public class PhoneNumber {
private String phoneNumber;
private String heldFromDate; // Bad design. This ought to be a Date, not a String
private String heldToDate; // Bad design. This ought to be a Date, not a String
public PhoneNumber() {
this("", "", "");
}
public PhoneNumber(String phoneNumber, String heldFromDate, String heldToDate) {
this.phoneNumber = phoneNumber;
this.heldFromDate = heldFromDate;
this.heldToDate = heldToDate;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getHeldFromDate() {
return heldFromDate;
}
public void setHeldFromDate(String heldFromDate) {
this.heldFromDate = heldFromDate;
}
public String getHeldToDate() {
return heldToDate;
}
public void setHeldToDate(String heldToDate) {
this.heldToDate = heldToDate;
}
}
Check if you have another class called Customer in the package practo. That would cause a name conflict.

Categories

Resources