public void loadFromFile() {
System.out.println("Loading books...");
FileInputStream fileInput = null;
try {
fileInput = new FileInputStream("books.txt");
Scanner sc = new Scanner(fileInput);
if (sc.hasNext()) {
System.out.format("%-5s %-45s %-10s", "Id", "Name", "Price");
System.out.println();
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
} else {
System.out.println("(empty)");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.err.println("File not found");
} finally {
try {
fileInput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// TODO: your code here
}
i have a .txt file with the requirement a program reads it and parses it into object. Each line is an object including attributes id, name and price
how can I parse text to object
public static final class Book {
private int id;
private String name;
private double price;
}
public static void main(String... args) throws FileNotFoundException {
List<Book> books = readMovies(new File("a.txt"));
}
private static List<Book> readMovies(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
scan.useLocale(Locale.ENGLISH);
List<Book> books = new ArrayList<>();
while (scan.hasNext()) {
Book book = new Book();
book.id = scan.nextInt();
String line = scan.nextLine().trim();
int pos = line.indexOf(" ");
book.name = line.substring(0, pos).trim();
book.price = Double.parseDouble(line.substring(pos + 1).trim());
books.add(book);
}
return books;
}
}
// this code can help you, happy to help
import java.io.*;
public class FileTextCheck {
public static void main(String[] args) {
User u1 = new User("Sudhakar", 27, "Male");
User u2 = new User("Richa", 25, "Female");
try {
FileOutputStream fos = new FileOutputStream(new File("/home/orange/Desktop/myfile.txt"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(u1);
oos.writeObject(u2);
oos.close();
fos.close();
FileInputStream fis = new FileInputStream(new File("/home/orange/Desktop/myfile.txt"));
ObjectInputStream ois = new ObjectInputStream(fis);
User pr1 = (User) ois.readObject();
User pr2 = (User) ois.readObject();
System.out.println(pr1.toString());
System.out.println(pr2.toString());
ois.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
private String gender;
User(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
#Override
public String toString() {
return "Name:" + name + "\nAge: " + age + "\nGender: " + gender;
}
}
}
You cannot parse any type of text to a java object. The text should be in JSON format. You can parse JSON string to java object using Gson library.
Related
I am making a program where user inputs his/her info and it is written in the file in binary form and after that we ask for a name whose info we want to get from the file. In that I take all the inserted objects into a arraylist and then match the name with respective name corresponding to the objects
this is my code
import java.util.*;
import java.io.*;
class MyObjectOutputStream extends ObjectOutputStream {
public MyObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
#Override
protected void writeStreamHeader() {}
}
interface IIITN {
final String InstituteName = "IIIT Nagpur";
}
class Student implements Serializable
{
String name;
String RollNo;
String branch;
String gender;
String Degree;
Student(String name, String RollNo, String branch, String gender, String Degree) {
this.name = name;
this.RollNo = RollNo;
this.branch = branch;
this.gender = gender;
this.Degree = Degree;
}
}
class CSE implements IIITN {
String name;
public void input(File CSEStudent) throws IOException {
Scanner sc = new Scanner(System.in);
String name = sc.next();
String RollNo = sc.next();
String branch = sc.next();
String gender = sc.next();
String Degree = sc.next();
Student s1 = new Student(name, RollNo, branch, gender, Degree);
FileOutputStream fs = new FileOutputStream(CSEStudent,true);
MyObjectOutputStream obj = new MyObjectOutputStream(fs);
obj.writeObject(s1);
// obj.close();
}
public void display(File f) throws IOException {
FileInputStream CS = new FileInputStream(f);
// ObjectInputStream obj = new ObjectInputStream(CS);
// ArrayList<Student> objectList = new ArrayList<>();
Student s = null;
boolean isExist = false;
ObjectInputStream obj = new ObjectInputStream(CS);
while (!isExist) {
try {
// ObjectInputStream obj = new ObjectInputStream(CS);
s = (Student) obj.readObject();
if (s != null) {
System.out.println(s.name);
}
} catch (Exception e) {
System.out.println();
isExist = true;
}
}
}
public void setname(File f) throws IOException{
System.out.println("Enter the name of student");
Scanner sc = new Scanner(System.in);
this.name = sc.next();
ArrayList<Student> obj = new ArrayList<>();
display(f);
// for (Student student : obj) {
// System.out.println(student.name);
// }
// System.out.println("Enter");
// for (int i = 0; i < obj.size(); i++) {
// if((obj.get(i)).name == this.name) {
// System.out.println((obj.get(i)).name);
// System.out.println((obj.get(i)).RollNo);
// } else {
// System.out.println("Not Found");
// }
// }
}
}
public class Main {
public static void main(String[] args) throws IOException{
CSE c1 = new CSE();
File f = new File("./CSE.txt");
c1.input(f);
c1.input(f);
c1.setname(f);
}
}
It is taking the info of the student and is writing it in the file but when it comes to read from the file it gives me this error
Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 73720007
at java.base/java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:987)
at java.base/java.io.ObjectInputStream.<init>(ObjectInputStream.java:414)
at CSE.display(Main.java:61)
at CSE.setname(Main.java:82)
at Main.main(Main.java:187)
I have an ArrayList of items - name, account number and balance read from a .txt file. Why is the output twice? (I've only 4 lines in my file each containing- name; account number; balance)
I want things above blue line only. Why is it displaying twice?
This is my class to retrieve from file and print
class BankAccount{ //core banking facilities
PrintStream pw=System.out;
protected String name;
protected long accountNumber;
protected float balance=0;
public String choiceList="\n1.AddAccount\n2.Withdraw\n3.Deposit\n4.MyAccount";
public BankAccount(String name,long accountNumber,float balance){
this.accountNumber=accountNumber;
this.name=name;
this.balance = balance;
}
public String getName(){
return this.name;
}
public long get_Account_no(){
return this.accountNumber;
}
public float get_Balance(){
return this.balance;
}
public BankAccount(){//loads from file to arraylist
BufferedReader in = null;
ArrayList <BankAccount> customer_list=new ArrayList<BankAccount>();
try {
in = new BufferedReader(new FileReader("bankfile.txt"));
String str;
while ((str = in.readLine()) != null) {
String[] temp_list=str.split(";");
accountNumber=Long.parseLong(temp_list[1]);
balance=Float.parseFloat(temp_list[2]);
BankAccount customer = new BankAccount(temp_list[0],accountNumber,balance);
customer_list.add(customer);
}
}catch (FileNotFoundException e) {e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
} finally {
if (in != null) {
try{ in.close();
} catch(Exception e){e.printStackTrace();}
}
}
for(BankAccount c: customer_list) pw.println(c.getName()+" "+c.get_Balance()+"\n");
}
}
and my main is-
class banker {
public static void main(String args[]){
additional_functionality af=new additional_functionality();
BankAccount ba=new BankAccount();
ba.pw.println("This is.. \n \t\tTHE BANK\nplease wait...");
String ch=JOptionPane.showInputDialog(ba.choiceList);
Integer choice=Integer.parseInt(ch);
switch(choice){
case 1: af.addAcount();
break;
case 4: //af.findAccount();
break;
default: JOptionPane.showMessageDialog(null,"Wrong Choice!","ERR",JOptionPane.ERROR_MESSAGE);
}System.exit(0);
}
my text file is-
bankfile.txt
Sorry, i'm not getting error. Hope this will helps you. I think that problem is that you twice run this constructor. Also, I run your code. And it's works.
My Main.java
public class Main {
public static void main(String[] args) {
// write your code
new BankAccount();
}
}
My file bankfile.txt
lala;0;0
coca;0;1
bola;1;1
My BankAccount.java
import java.io.*;
import java.util.ArrayList;
public class BankAccount {
private String name;
private long accountNumber;
private float balance;
public BankAccount(){//loads from file to arraylist
BufferedReader in = null;
ArrayList<BankAccount> customer_list=new ArrayList<BankAccount>();
try {
in = new BufferedReader(new FileReader("bankfile.txt"));
String str;
while ((str = in.readLine()) != null) {
String[] temp_list=str.split(";");
accountNumber=Long.parseLong(temp_list[1]);
balance=Float.parseFloat(temp_list[2]);
BankAccount customer = new BankAccount(temp_list[0],accountNumber,balance);
customer_list.add(customer);
}
for(BankAccount c: customer_list) System.out.println(c.getName()+" "+c.get_Balance());
}catch (FileNotFoundException e) {e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
} finally {
if (in != null) {
try{ in.close();
} catch(Exception e){e.printStackTrace();}
}
}
}
public BankAccount(String name, Long accountNumber, float balance){
this.name = name;
this.balance = balance;
this.accountNumber = accountNumber;
}
public String getName() {
return name;
}
public long getAccountNumber() {
return accountNumber;
}
public float get_Balance() {
return balance;
}
}
I need to store an ArrayList of type "Comment" in my SharedPreferences. This is my model class:
public class Comment {
public String getPID() {
return PID;
}
public void setPID(String pID) {
PID = pID;
}
public String PID;
public String Comment;
public String Commenter;
public String Date;
public String getComment() {
return Comment;
}
public void setComment(String comment) {
Comment = comment;
}
public String getCommenter() {
return Commenter;
}
public void setCommenter(String commenter) {
Commenter = commenter;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
}
So my ArrayList contains 2 Comments that need to be stored in SharedPreferences. I tried HashSet but it requires String values:
ArrayList<Comment_FB> fb = getFeedback(); //my Comments List
SharedPreferences pref = getApplicationContext().getSharedPreferences("CurrentProduct", 0);
Editor editor = pref.edit();
Set<String> set = new HashSet<String>();
set.addAll(fb);
editor.putStringSet("key", set);
editor.commit();
How do I get this done folks? :)
I think you need to store it as a file.
public static boolean save(String key, Serializable obj) {
try {
FileOutputStream outStream = new FileOutputStream(instance.getCacheDir() + "/" + key);
ObjectOutputStream objOutStream;
objOutStream = new ObjectOutputStream(outStream);
objOutStream.writeObject(obj);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public static Object getObject(String key) {
Object obj = null;
if (!new File(instance.getCacheDir() + "/" + key).exists())
return obj;
FileInputStream inputStream;
try {
inputStream = new FileInputStream(instance.getCacheDir() + "/" + key);
ObjectInputStream objInputStream = new ObjectInputStream(inputStream);
obj = objInputStream.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
Your "Comment" class should implements Serializable.
So, I'm trying to read in an Object from a file, and I can't figure out why I'm getting this exception, or how to fix it. Maybe you guys can help me out? I've tried messing around with the way I read the object, but can't get it quite right. Here is my code I'm getting the error on the line that reads listOfEmployeesIn[i] = (Employee) objIn.readObject();:
import java.util.Random;
import java.io.*;
public class ProjectFive{
public static void main(String[] args) throws IOException{
Random rn = new Random();
RandomAccessFile file = new RandomAccessFile("employees.txt", "rw");
FileOutputStream fileOut = new FileOutputStream("employees.txt");
ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
FileInputStream fileIn = new FileInputStream("employees.txt");
ObjectInputStream objIn = new ObjectInputStream(fileIn);
Object x;
long SSN;
float salary;
int age;
float maxSalary = 200000;
float minSalary = 20000;
long SSNRange = 1000000000;
String[] names = {"Matty Villa"};
Employee[] listOfEmployeesOut = new Employee[20];
Employee[] listOfEmployeesIn = new Employee[20];
for(int i=0;i<listOfEmployeesOut.length;i++){
SSN = (long)(rn.nextDouble()*SSNRange);
salary = rn.nextFloat()*(maxSalary - minSalary)+minSalary;
age = rn.nextInt(57)+18;
listOfEmployeesOut[i] = new Employee(SSN, names[i], salary, age);
}
for(int i = 0;i<listOfEmployeesOut.length;i++){
objOut.writeObject(listOfEmployeesOut[i]);
}
for(int i = 0;i<listOfEmployeesIn.length;i++){
listOfEmployeesIn[i] = (Employee) objIn.readObject();
}
file.close();
fileOut.close();
objOut.close();
fileIn.close();
objIn.close();
}
}
class Employee implements Serializable{
public long socialSecurityNumber;
public String fullName;
public float salary;
public int age;
public Employee(long socialSecurityNumber, String fullName, float salary, int age){
this.socialSecurityNumber = socialSecurityNumber;
if(fullName.length() != 50){
fullName = resizeString(fullName);
}
this.fullName = fullName;
this.salary = salary;
this.age = age;
}
private String resizeString(String s){
if(s.length() < 50){
for(int i = s.length(); i<=50; i++){
s += ' ';
}
}else{
s = s.substring(0,50);
}
return s;
}
public String toString(){
String out = "Name: " + fullName + "\nSalary: " + salary + "\nSocial: " + socialSecurityNumber
+ "\nAge: " + age;
return out;
}
}
As per JAVA API for ObjectInputStream, the method readObject throws checked exceptions - IOException, ClassNotFoundException
So either throw this exception from main method:
public static void main(String[] args) throws IOException, ClassNotFoundException
or handle it using try/catch blocks:
try {
listOfEmployeesIn[i] = (Employee) objIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
I have a program in which I read a CSV file and export a text file type.
CSV attributes are name, date of birth, email and address.
I need a BufferedReader through a user can insert the email of one of the records and delete the entire row in the CSV (deleting name, date of birth, and email address) and re-export the text file type.
I do not have much knowledge of Java so much that could help me guide me to the solution.
I share the code,
Help is appreciated,
Thank you!
public class Personas {
private String nombre;
private String fechaNacimiento;
private String email;
private String direccion;
public Personas(String nombre, String fechaNacimiento, String email,
String direccion) {
super();
this.nombre = nombre;
this.fechaNacimiento = fechaNacimiento;
this.email = email;
this.direccion = direccion;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(String fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
}
Here is the main class
import java.io.*;
public class Principal {
public static void main(String[] args) {
// TODO Auto-generated method stub
Personas[] miLista = new Personas[100];
int i = 0;
String texto = "";
FileReader lector;
try {
lector = new FileReader("C:\\Users\\CD\\Downloads\\dummydata.csv");
BufferedReader contenido=new BufferedReader(lector);
try {
while((texto=contenido.readLine())!=null){
String[] valores = texto.split(",");
Personas persona = new Personas(valores[0], valores[1], valores[2], valores[3]);
miLista[i]=persona;
i++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("hay mas de 100 registros en el archivo");
System.out.println("solo se cargaran los primeros 100");
}catch(Exception e){
System.out.println("error desconocido contacte con el desarrollador...");
System.out.println(e.getMessage());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.print("El archivo no se encuentra...");
}catch(Exception e){
System.out.println("error desconocido contacte con el desarrollador...");
System.out.println(e.getMessage());
}
for (Personas persona : miLista) {
System.out.print(persona.getNombre());
System.out.print(persona.getDireccion());
System.out.print(persona.getFechaNacimiento());
System.out.println(persona.getEmail());
}
File miArchivo = new File("miNuevoArchivo.txt");
try{
FileWriter fw = new FileWriter(miArchivo);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter wr = new PrintWriter(bw);
for (Personas persona : miLista) {
wr.write(persona.getNombre()+"\t");
wr.append(persona.getFechaNacimiento()+"\t");
wr.append(persona.getDireccion()+"\t");
wr.println(persona.getEmail());
}
wr.close();
bw.close();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
}
I hope it help... but not sure it's what you want to do.
Try to not mix differents languages, see try-with-resource, use List (ArrayList) instead of Arrays, create simple functions and read some docs about iterator.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Principal {
private static final String IN = "C:\\Users\\CD\\Downloads\\dummydata.csv";
private static final String OUT = "C:\\Users\\CD\\Downloads\\result.txt";
public static List<Personas> readFile(final String file) throws Exception {
final List<Personas> result = new ArrayList<Personas>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String texto = "";
while ((texto = reader.readLine()) != null) {
final String[] valores = texto.split(",");
final Personas persona = new Personas(valores[0], valores[1], valores[2], valores[3]);
result.add(persona);
}
}
return result;
}
public static void write(final String file, final List<Personas> personas) throws Exception {
new File(file);
try (PrintWriter wr = new PrintWriter(new File(file))) {
for (final Personas persona : personas) {
wr.write(persona.getNombre() + "\t");
wr.append(persona.getFechaNacimiento() + "\t");
wr.append(persona.getDireccion() + "\t");
wr.println(persona.getEmail());
}
}
}
public static void main(final String[] args) throws Exception {
final List<String> emailsToRemove = Arrays.asList("email1#lol.com", "email2#lol.com");
final List<Personas> personas = readFile(IN);
//Remove some personnas
for (Iterator<Personas> it = personas.iterator(); it.hasNext(); /**RIEN**/) {
Personas act = it.next();
if(emailsToRemove.contains(act.getEmail())){
it.remove();
}
}
write(OUT, personas);
}
}