Modify whole line of data in txt file using java - java

So I have this console app with line of Java code intended to modify the Book data inside txt file.
User will prompted to enter the book ID of the book that is going to be modified and then just basically enter all the book details.
public void UpdatingBookData()
{
int bid; String booktitle; String author; String desc; String Alley;
System.out.println("Enter Book ID: ");
bid = sc.nextInt();
System.out.println("Enter Book Title: ");
booktitle = sc.next();
System.out.println("Enter Book Author: ");
author = sc.next();
System.out.println("Enter Book Description: ");
desc = sc.next();
System.out.println("Enter Book Alley: ");
Alley = sc.next();
UpdateBook(bid, booktitle, author, desc, Alley);
}
public static void UpdateBook(int bid, String booktitle, String author, String desc, String Alley)
{
ArrayList<String> TempArr = new ArrayList<>();
try
{
File f = new File("book.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line;
String[] lineArr;
line = br.readLine();
while(line != null)
{
lineArr = line.split(" ");
if(lineArr[0].equals(bid))
{
TempArr.add(
bid + " " +
booktitle + " " +
author + " " +
desc + " " +
Alley );
}
else
{
TempArr.add(line);
}
}
fr.close();
}
catch(IOException ex)
{
System.out.println(ex);
}
try
{
FileWriter fw = new FileWriter("book.txt");
PrintWriter pw = new PrintWriter(fw);
for(String str : TempArr)
{
pw.println(str);
}
pw.close();
}
catch(IOException ex)
{
System.out.println(ex);
}
}
but when I run it, I keep receiving this error
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:261)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
at java.util.ArrayList.add(ArrayList.java:458)
at lmsconsole.Administrator.UpdateBook(Administrator.java:438)
at lmsconsole.Administrator.UpdatingBookData(Administrator.java:409)
at lmsconsole.Administrator.adminPanel(Administrator.java:52)
at lmsconsole.MainMenu.loginAdmin(MainMenu.java:68)
at lmsconsole.MainMenu.MainPanel(MainMenu.java:45)
at lmsconsole.LMSConsole.main(LMSConsole.java:24)
Is it because of the ArrayList or what? Thanks in advance!

Related

Adding text at the beginning of a file Java

This is a project for school, and I am having difficulty figuring out why it is this way. We are to create a program that will put data into a text file, but whenever I run my code, it will output to the file, but it will be at line 224, and not start at the beginning. Does anyone know why this may be? Here is my code
import java.nio.file.*;
import java.io.*;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
import java.nio.channels.FileChannel;
public class CreateCustomerFile
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Path file = Paths.get("C:\\Users\\brady\\IdeaProjects\\TestNew\\Customers.txt");
String s = "000, ,00000" + System.getProperty("line.separator");
String[] array;
byte[] data = s.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(data);
FileChannel fc = null;
final int recordSize = s.length(); //Size of record
final int recordNums = 1000; //Number of records stored in file
final String QUIT = "exit";
String custString;
int custNum;
String lastName;
String zipCode;
String fileNum;
try
{
OutputStream output = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
for(int count = 0; count < recordNums; ++count)
writer.write(s, 0, s.length());
writer.close();
}
catch(Exception e)
{
System.out.println("Error message: " + e);
}
try
{
fc = (FileChannel)Files.newByteChannel(file, READ, WRITE);
System.out.print("Enter customer number or 'exit' to quit >> ");
custString = input.nextLine();
while(!(custString.equalsIgnoreCase(QUIT)))
{
custNum = Integer.parseInt(custString);
buffer = ByteBuffer.wrap(data);
fc.position((long) custNum * recordSize);
fc.read(buffer);
s = new String(data);
array = s.split(",");
fileNum = array[0];
if(!(fileNum.equals("000")))
System.out.println("Sorry - customer " + custString + " already exists");
else
{
System.out.print("Enter the last name for customer #" + custNum + ": ");
lastName = input.nextLine();
StringBuilder sb = new StringBuilder(lastName);
sb.append(" ");
sb.setLength(6);
lastName = sb.toString();
System.out.print("Enter zip code: ");
zipCode = input.nextLine();
s = custString + "," + lastName + "," + zipCode + System.getProperty("line.separator");
data = s.getBytes();
buffer = ByteBuffer.wrap(data);
fc.position((long) custNum * recordSize);
fc.write(buffer);
}
System.out.print("Enter next customer number or 'exit' to quit: ");
custString = input.nextLine();
}
fc.close();
}
catch (Exception e)
{
System.out.println("Error message: " + e);
}
}
}
Your code needs more input validation, any user provided string input must be sized for the output field, no matter the input.
lastName is done correctly, but customer number and zip code are left to chance, and can throw off the record count in the file.
A customer id entered as "1" is 2 characters shorter than "001" thus upsetting the fixed length record for the remaining file.

Can't store inputs from JTextField to filewriter

I'm trying to make a phone directory where the user has to enter multiple inputs using JTextField. I also have a search option that will search the inputted name from the directory in filewriter and I just can't seem to store my inputs in the filewriter. This is my initial code
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int menu = 0;
boolean quit = false;
do{
String input = JOptionPane.showInputDialog(null,"Telephone Directory Management System"
+ "\n1. Add a Student"
+ "\n2. Search"
+ "\n3. Sort Data"
+ "\n4. List of all data"
+ "\n5. Exit"
+ "\n\nPlease enter your choice:","Main Menu",JOptionPane.QUESTION_MESSAGE);
menu = Integer.parseInt(input);
switch (menu) {
case 1:
JTextField student = new JTextField();
JTextField name = new JTextField();
JTextField address = new JTextField();
JTextField phone = new JTextField();
Object[] fields = {
"Enter Student ID:",student,
"Enter Name:",name,
"Enter Address:",address,
"Enter Phone No.:",phone};
int add = JOptionPane.showConfirmDialog(null,fields,"Add a Student",JOptionPane.OK_CANCEL_OPTION);
if (add == JOptionPane.OK_OPTION)
{
String student1 = student.getText();
String name1 = name.getText();
String address1 = address.getText();
String phone1 = phone.getText();
FileWriter fw = new FileWriter(new File("directory.txt"), true);
BufferedWriter out = new BufferedWriter(fw);
out.write(student1 + " " + name1 + " " + address1 + " " + phone1);
out.newLine();
}
break;
case 2:
input = JOptionPane.showInputDialog(null,"Enter name to search information:","Search",JOptionPane.OK_CANCEL_OPTION);
File f = new File("directory.txt");
try {
BufferedReader freader = new BufferedReader(new FileReader(f));
String s;
while ((s = freader.readLine()) != null) {
String[] st = s.split(" ");
String id = st[0];
String nm = st[1];
String add1 = st[2];
String phoneNo = st[3];
if (input.equals(nm)) {
JOptionPane.showMessageDialog(null,"Student ID: "+id+"\nName: "+nm+"\nAddress: "+add1+"\nPhone No.: "+phoneNo+"","Information",JOptionPane.QUESTION_MESSAGE);
}
}
freader.close();
} catch (Exception e) {
}
break;
I tried using scanner before and it does store my inputs but I need to use JOptionPane in this one. Thank you so much to anyone that can help me in this.
You should close the BufferedWriter after writing into it, like this
out.close()
If you don't do this the BufferedWriter won't flush what you've written into it to the underlying stream.

I've trying to use tokenizer to set name and surname

public static Player newPlayer(Integer playerNum){
Player player = new Player();
System.out.println("Player " + (playerNum+1) + " registration");
try {
String fullname = null;
StringTokenizer lineTokens = new StringTokenizer(fullname);
System.out.print("Name: ");
String name = input.readLine();
String surname = input.readLine();
fullname = input.readLine();
player.setName(name + surname);
while (lineTokens.hasMoreTokens()) {
if ( lineTokens.countTokens() >= 0 ) {
name = lineTokens.nextToken();
surname = lineTokens.nextToken();
fullname = (name+" "+surname);
} else {
String checkSpace = lineTokens.nextToken();
for (int i = 0; i < checkSpace.length(); i++) {
if ( checkSpace.charAt(i) == ' ' ) {
break;
}
}
}
}
}catch (IOException e){}
}
I need to set a name and a surname using Tokenizer it is crashing.
P.S I want learn how to use it instead of the split
I didn't understand exactly what you wanted to do, below is a short script to read first and last name from the user, using StringTokenizer
public static void main(String[] args) {
System.out.println("Enter name: <firstName> <lastName>");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
StringTokenizer tokenizer = new StringTokenizer(input, " ");
String firstName = "";
String lastName = "";
if (tokenizer.countTokens() >= 2){
firstName = tokenizer.nextToken();
lastName = tokenizer.nextToken();
}
System.out.println("first name is " + firstName);
System.out.println("last name is " + lastName);
}

Writing more details in a file

actually am working on files and i have written exactly one person's details to a file ,now i want to write multiple person's details to that
file,i have tried using for loop but two files has been created and i want to write multiple person's details in the same file
import java.util.*;
import java.io.*;
public class Tourism {
String name;
String contact_number;
String address;
String enquiry_category;
String Des;
String price;
String location;
String packages;
Scanner s=new Scanner(System.in);
Scanner s1=new Scanner (System.in);
Scanner s2=new Scanner(System.in);
Scanner s3=new Scanner(System.in);
Scanner s4=new Scanner(System.in);
Scanner scan=new Scanner(System.in);
public void Choice(){
System.out.println("========menu========");
System.out.println("1.Initiate enquiry");
System.out.println("2.view enquiry");
System.out.println("3.exit");
System.out.println("enter the choice");
int ch;
ch=scan.nextInt();
switch(ch){
case 1:initiate();
break;
case 2:
View();
break;
case 3:
System.exit(0);
break;
}
}
public void initiate(){
for(int i=1;i<=2;i++){
System.out.println("=========="+i+"=========");
System.out.println("enter the name");
name=s.next();
System.out.println("enter the contact number");
contact_number=s1.nextLine()+"";
System.out.println("enter the address");
address=s2.nextLine()+"";
System.out.println(" enquiry categories:-");
System.out.println("enter the price range");
price=s1.nextLine()+"";
System.out.println("enter the location");
location=s2.nextLine()+"";
System.out.println("select/enter the package u want to have");
packages=s3.nextLine()+"";
System.out.println("enter the description of enquiry");
Des=s4.nextLine()+"";
}
try{
BufferedWriter br=new BufferedWriter(new FileWriter("Enquiry.txt"));
br.write(name);
br.newLine();
br.write("mobile number:"+contact_number);
br.newLine();
br.write("address:"+address);
br.newLine();
br.write("price:"+price);
br.newLine();
br.write("location:"+location);
br.newLine();
br.write("packages:"+packages);
br.newLine();
br.write("enquiry description:"+Des);
br.close();
}catch(IOException e){
System.out.println(e);
}
}
public void View(){
Scanner scanner=new Scanner(System.in);
System.out.println("enter the name to view the details");
String name1;
name1=scanner.nextLine();
try{
BufferedReader br=new BufferedReader(new FileReader("C:\\Users\\shashi.s\\Documents\\NetBeansProjects\\JavaApplication128\\Enquiry.txt"));
String line;
while((line=br.readLine())!=null){
if(line.equals(name1)){
System.out.println(line);
String line1;
while((line1=br.readLine())!=null){
System.out.println(line1);
}
}else{
System.out.println("oops "+name1+" .....does not exist");
break;
}
}
}catch(IOException e){
System.out.println(e);
}
}
public static void main(String[] args) {
Tourism t=new Tourism();
t.Choice();
}
}
use FileWriter(String fileName, boolean append)
instead of **new FileWriter("Enquiry.txt")**
the modified code tells to append text when boolean expression is true. but in your case it is only writing instead of appending next entered data.Hope you found my code helpful.
In your iteration you are just getting the values from console and storing to the variables,but not writing to the file.When you enter the second set of values it overwrites the first one.Finally, you come out of the loop and write the values to file.But the variables only hold the last entered values.
You can modify your code to write to the file,within the for loop itself,as modified below:
public void initiate() {
try {
BufferedWriter br = new BufferedWriter(new FileWriter("Enquiry.txt"));
for (int i = 1; i <= 2; i++) {
System.out.println("==========" + i + "=========");
System.out.println("enter the name");
name = s.next();
System.out.println("enter the contact number");
contact_number = s1.nextLine() + "";
System.out.println("enter the address");
address = s2.nextLine() + "";
System.out.println(" enquiry categories:-");
System.out.println("enter the price range");
price = s1.nextLine() + "";
System.out.println("enter the location");
location = s2.nextLine() + "";
System.out.println("select/enter the package u want to have");
packages = s3.nextLine() + "";
System.out.println("enter the description of enquiry");
Des = s4.nextLine() + "";
br.newLine();
br.write(name);
br.newLine();
br.write("mobile number:" + contact_number);
br.newLine();
br.write("address:" + address);
br.newLine();
br.write("price:" + price);
br.newLine();
br.write("location:" + location);
br.newLine();
br.write("packages:" + packages);
br.newLine();
br.write("enquiry description:" + Des);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
}

java - Scanner class NoSuchElementFoundException [duplicate]

This question already has answers here:
NoSuchElementException with Java.Util.Scanner
(10 answers)
Closed 9 years ago.
I am trying a program in Java. My code goes as follows
class Main{
static Employee getData() throws IOException {
BufferedReader rdr = new BufferedReader(
new InputStreamReader(
new DataInputStream(System.in)
));
System.out.printf("Enter Employee ID : ");
int tmpid = Integer.parseInt(rdr.readLine());
System.out.printf("Enter Employee Name : ");
String tmpname = rdr.readLine();
System.out.printf("Enter Employee Salary : ");
int tmpsalary = Integer.parseInt(rdr.readLine());
rdr.close();
return new Employee(tmpid, tmpname, tmpsalary);
}
public static void main(String []args){
boolean b = false;
String path = null;
Scanner s = new Scanner(System.in);
File file = null;
try {
System.out.printf("Enter path to save your file : ");
path = s.next();
file = new File(path);
if (!(file.createNewFile()))
System.out.println("Error creating file");
} catch (Exception ie) {
System.err.println("Exception : " + ie);
}
do{
try {
Employee rec = Main.getData();
ObjectOutputStream dos = new ObjectOutputStream(new FileOutputStream(file));
dos.writeObject(rec);
dos.close();
System.out.printf("Add more records [true/false]? ");
s = new Scanner(System.in);
int tmp = s.nextInt();
} catch (Exception ioe) {
System.err.println("Exception : " + ioe);
}
}while(b);
}
}
When I run this program I get NoSuchElementFoundException when second time s.nextInt() is executed. I tried out every possible methods but with no result. What is the problem over here?
Never catch an exception unless you are going to do something useful with it.
I got it to work. It was fairly straight forward.
Enter path to save your file : myfile.bin
Enter Employee ID : 99
Enter Employee Name : Rick Hightower
Enter Employee Salary : 99
Add more records [true/false]? true
Enter Employee ID : 77
Enter Employee Name : Dippy Do
Enter Employee Salary : 88
Add more records [true/false]? false
Here is what I have:
...
public static class Employee implements Serializable {
int id;
String name;
int salary;
public Employee(int id, String name, int salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
}
static Employee getData() throws IOException {
BufferedReader rdr = new BufferedReader(
new InputStreamReader(
new DataInputStream(System.in)
));
System.out.printf("Enter Employee ID : ");
int tmpid = Integer.parseInt(rdr.readLine());
System.out.printf("Enter Employee Name : ");
String tmpname = rdr.readLine();
System.out.printf("Enter Employee Salary : ");
int tmpsalary = Integer.parseInt(rdr.readLine());
//rdr.close(); this is why... you broke it :)
return new Employee(tmpid, tmpname, tmpsalary);
}
public static void main(String []args) throws Exception {
boolean moreRecords = true;
String path = null;
Scanner scanner = new Scanner(System.in);
File file = null;
System.out.printf("Enter path to save your file : ");
path = scanner.next();
file = new File(path);
while (moreRecords) {
Employee rec = Main.getData();
ObjectOutputStream dos = new ObjectOutputStream(new FileOutputStream(file));
dos.writeObject(rec);
dos.close();
System.out.printf("Add more records [true/false]? ");
moreRecords = scanner.nextBoolean();
}
It is mostly your code with some parts taken away.
The biggest issue you had was you were closing the input stream.
static Employee getData() throws IOException {
BufferedReader rdr = new BufferedReader(
new InputStreamReader(
new DataInputStream(System.in)
));
System.out.printf("Enter Employee ID : ");
int tmpid = Integer.parseInt(rdr.readLine());
System.out.printf("Enter Employee Name : ");
String tmpname = rdr.readLine();
System.out.printf("Enter Employee Salary : ");
int tmpsalary = Integer.parseInt(rdr.readLine());
//rdr.close(); this is why... you broke it :) <-------------------SEE
return new Employee(tmpid, tmpname, tmpsalary);
}
The Java I/O stream uses the decorator pattern so it just keeps delegating the close call into the inner streams.
That fixes that problem. There are lots of problems with your code.
If you are using JDK 1.7 or later, it will close the file for you.
while (moreRecords) {
Employee rec = Main.getData();
try ( ObjectOutputStream dos =
new ObjectOutputStream(
new FileOutputStream(file) ) ) {
dos.writeObject(rec);
}
System.out.printf("Add more records [true/false]? ");
moreRecords = scanner.nextBoolean();
}
If you are using JDK 1.6 or JDK 1.5:
while (moreRecords) {
Employee rec = Main.getData();
ObjectOutputStream dos = null;
try {
dos = new ObjectOutputStream(
new FileOutputStream(file) );
dos.writeObject(rec);
} finally {
if ( dos!=null ) {
dos.close();
}
}
System.out.printf("Add more records [true/false]? ");
moreRecords = scanner.nextBoolean();
}
Also, your program should do more validation of user input. Scanner can do that as follows:
public static class Employee implements Serializable {
private int id;
private String name;
private BigDecimal salary;
public Employee(int id, String name, BigDecimal salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
}
static Employee getData(Scanner scanner) throws IOException {
System.out.printf("Enter Employee ID : ");
while ( !scanner.hasNextInt() ) {
System.out.println("Employee IDs are numbers only");
scanner.next();
}
int employeeId = scanner.nextInt();
System.out.printf("Enter Employee Name : ");
String name = scanner.next();
System.out.printf("Enter Employee Salary : ");
while ( !scanner.hasNextBigDecimal() ) {
System.out.println("Employee salaries are decimals " +
"not random gak");
scanner.next();
}
BigDecimal salary = scanner.nextBigDecimal();
return new Employee(employeeId, name, salary);
}
public static void main(String []args) throws Exception {
boolean moreRecords = true;
String path = null;
Scanner scanner = new Scanner(System.in);
File file = null;
System.out.printf("Enter path to save your file : ");
path = scanner.next();
file = new File(path);
while (moreRecords) {
Employee rec = Main.getData(scanner);
try ( ObjectOutputStream dos =
new ObjectOutputStream(
new FileOutputStream(file) ) ) {
dos.writeObject(rec);
}
System.out.printf("Add more records [true/false]? ");
moreRecords = scanner.nextBoolean();
Now the input/output is more like this:
Enter path to save your file : asdfasdf
Enter Employee ID : 9a
Employee IDs are numbers only
99
Enter Employee Name : Rick
Enter Employee Salary : aa
Employee salaries are decimals not random gak
99.99
Add more records [true/false]? false
The scanner forces the end user to enter in the right types of data.
You can combine it with regex to match patterns for names, etc.
I extended the example and added some discussion of the Scanner.
http://rick-hightower.blogspot.com/2013/10/java-scanner-example.html
In nextInt(), NoSuchElementFoundException occurs when the input is exhausted. So check the input that you give at prompt.

Categories