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.
Related
I'm using NetBeans 16 and I'm trying to add the ability to edit a record from a text file I have saved separated by commas.
Ive tried this code here and I don't seem to get any errors (except the one produced as a result of the try catch) but I have no idea why this doesn't seem to work when I try to overwrite a record which I have selected ive tried everything I can think of I'm pretty new to coding so forgive me if there's some obvious error but I have no idea why this doesn't work my text file has 5 entries in a row if that helps but yeah any help is greatly appreciated
public class EditRecords {
private static Scanner x;
public static void main(String[]args)
{
String filepath = "VehicleInforUpd.txt";
System.out.println("Enter Registration of Entry You Wish To Edit");
Scanner scanner = new Scanner(System.in);
String editTerm = scanner.nextLine();
System.out.println("Enter new Registration: ");
String newReg = scanner.nextLine();
System.out.println("Enter new Make: ");
String newMake = scanner.nextLine();
System.out.println("Enter New Model: ");
String newModel = scanner.nextLine();
System.out.println("Enter New Year: ");
String newYear = scanner.nextLine();
System.out.println("Enter New Comments: ");
String newComment = scanner.nextLine();
editRecord(filepath,editTerm,newReg,newMake,newModel,newYear,newComment);
}
public static void editRecord(String filepath,String editTerm,String newReg,String newMake,String newModel, String newYear, String newComment)
{
String tempFile = "temp.txt";
File oldFile = new File(filepath);
File newFile = new File(tempFile);
String reg = ""; String make = ""; String model = ""; String year = ""; String comment = "";
try
{
FileWriter fw = new FileWriter(tempFile,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
while(x.hasNext())
{
reg = x.next();
make = x.next();
model = x.next();
year = x.next();
comment = x.next();
if(reg.equals(editTerm))
{
pw.println(newReg+","+newMake+","+newModel+","+ newYear+","+newComment);
}
else
{
pw.println(reg+","+make+","+model+","+year+","+comment);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
JOptionPane.showMessageDialog(null, "Changes Succesfully Saved");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
The Print stack trace results but im not sure what would cause the NullPointerException im getting
java.lang.NullPointerException
at com.mycompany.anprsystems.EditRecords.editRecord(EditRecords.java:70)
at com.mycompany.anprsystems.EditRecords.main(EditRecords.java:52)
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.
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!
This is my current output:
********MENU********
1. UNIT
2. EXIT
*********************
Select your option from 1 or 2: 1
********MENU********
1. VIEW LIST
2. BACK TO MAIN
*********************
Select your option from 1 or 2: 1
This are the list of the units:
[1] Asero/California
[2] Captain America/Pennsylvania
What unit do you want to modify? 1
Asero/California
Asero/California
Unit Name: Iron Man
Unit Location: California
Return to menu? Select 1: 1
********MENU********
1. VIEW LIST
2. BACK TO MAIN
*********************
Select your option from 1 or 2: 1
This are the list of the units:
[1] Asero/California
[2] Captain America/Pennsylvania
What unit do you want to modify?
Process interrupted by user.
What I wanted is the "Asero/California" is modified and replaced into "Iron Man/California".
The original output is still:
[1] Asero/California
[2] Captain America/Pennsylvania
My desired output is when I modify the data it should now be:
[1] Iron Man/California
[2] Captain America/Pennsylvania
I have a textfile = "practice.txt", which is where the data is stored.
I also have another text file = "tempPractice.txt", which is used just for putting a temporary data.
public class Practice
{
List<String> lines = new ArrayList<String>();
public Practice()
{
try
{
String line = "";
System.out.println("********MENU********");
System.out.println("1. UNIT");
System.out.println("2. EXIT");
System.out.println("*********************");
System.out.print("Select your option from 1 or 2: ");
Scanner sc = new Scanner(System.in);
line = sc.next();
if(line.equals("1"))
{
unitMenu();
}
else if(line.equals("2"))
{
System.exit(0);
}
else
{
System.out.println("Incorrect code, please select from 1 or 2.");
new Practice();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void unitMenu()
{
try
{
String line = "";
System.out.println("********MENU********");
System.out.println("1. VIEW LIST");
System.out.println("2. BACK TO MAIN");
System.out.println("*********************");
System.out.print("Select your option from 1 or 2: ");
Scanner sc = new Scanner(System.in);
line = sc.next();
if(line.equals("1"))
{
updateData();
}
else if(line.equals("2"))
{
new Practice();
}
else
{
System.out.println("Incorrect code, please select from 1 or 2.");
unitMenu();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void updateData()
{
lines = new ArrayList<String>();
File f = new File("practice.txt");
BufferedReader bR, bR2;
BufferedWriter bW;
Scanner sc, sc2;
String str = "", scanLine, oldFile, newFile, tmpFile, uName, uLoc;
int numLine;
try
{
if(!f.exists())
{
System.out.println("File not found!");
}
else
{
bR = new BufferedReader(new FileReader("practice.txt"));
while((str = bR.readLine()) != null)
{
lines.add(str);
}
System.out.println();
System.out.println("This are the list of the units:");
for(int i=0,j=1;i<lines.size();i++,j++)
{
System.out.println( "[" + j + "] " + lines.get(i).toString());
}
System.out.print("What unit do you want to modify? ");
sc = new Scanner(System.in);
numLine = sc.nextInt();
int count = numLine;
--count;
for(int k=0;k<lines.size();k++)
{
if(count == k)
{
System.out.println(lines.get(k).toString());
//used for checking to know what data it returns
oldFile = lines.get(count).toString();
System.out.println(oldFile);
//method to replace a data --> not working/trial and error?
bW = new BufferedWriter(new FileWriter("tmpPractice.txt"));
System.out.print("Unit Name: ");
sc = new Scanner(System.in);
uName = sc.nextLine();
bW.write(uName);
bW.append('/');
System.out.print("Unit Location: ");
sc2 = new Scanner(System.in);
uLoc = sc2.nextLine();
bW.write(uLoc);
bW.newLine();
bW.close();
System.out.print("Return to menu? Select 1: ");
sc = new Scanner(System.in);
scanLine = sc.next();
if(scanLine.equals("1"))
{
unitMenu();
}
else
{
System.out.println("Error. Select only 1.");
updateData();
}
bR2 = new BufferedReader(new FileReader("tmpPractice.txt"));
while((newFile = bR2.readLine()) != null)
{
tmpFile = newFile;
oldFile = tmpFile;
bW = new BufferedWriter(new FileWriter("practice.txt", true));
bW.write(oldFile);
bW.close();
}
System.out.println(oldFile);
bR2.close();
}
bR.close();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] a)
{
new Practice();
}
}
How would I do it? What should I do or what should I use in my code?
Is there any simplier way to do this? Any feedback/suggestion/remarks/help would be deeply much appreciated.
I'm still new to Java, and I'm doing a lot of practice for myself, I reached up to the point where I can append a data to a file with IO, however, I still dont know how to modify/replace a specific data in the file without deleting all of its contents.
Please help me, I really want to learn more.
Take a look at this and modify accordingly.
public static void replaceSelected(String address) {
try {
String x = "t";
System.out.println("started searching for line");
File inputFile1 = new File(old file where line is to be updated);
File tempFile = new File(address+"/myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(old file "));
String lineToRemove = "add line to remove as a variable or a text";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove) && x.contentEquals("t")) {
x ="f";
} else if(trimmedLine.equals(lineToRemove) && x.contentEquals("f")) {
System.out.println("removed desired header");
System.out.println("Line"+trimmedLine);
continue;
}
FileWriter fw = new FileWriter(new file address,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(currentLine);
System.out.println(currentLine);
bw.write("\n");
bw.close();
}
// writer.close();
reader.close();
boolean success3 = (new File (old file address)).delete();
if (success3) {
System.out.println(" Xtra File deleted");
}
} catch (Exception e){
}
I have worked out this code. In my code I have not used the temp file instead used the arraylist in to replace the old value with the new one.And After that I have write down the arraylist to the file. Please see below the changed code. I have only included the changed code here. This is working for me now.
for(int k=0;k<lines.size();k++)
{
if(count == k)
{
System.out.println(lines.get(k).toString());
//used for checking to know what data it returns
oldFile = lines.get(count).toString();
System.out.println(oldFile);
System.out.print("Unit Name: ");
sc = new Scanner(System.in);
uName = sc.nextLine();
System.out.print("Unit Location: ");
sc2 = new Scanner(System.in);
uLoc = sc2.nextLine();
String replaceString = uName+"/"+uLoc;
lines.set(k, replaceString);
FileOutputStream fop = null;
fop = new FileOutputStream(f);
for(String content:lines){
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.write("\n".getBytes());
}
fop.flush();
fop.close();
System.out.print("Return to menu? Select 1: ");
sc = new Scanner(System.in);
scanLine = sc.next();
if(scanLine.equals("1"))
{
unitMenu();
}
else
{
System.out.println("Error. Select only 1.");
updateData();
}
}
bR.close();
}
You used String replaceString = ...? Is the replaceString a value or a variable??
replaceString is a variable that contains the user enterd value to
replace the desired string value in the file
Another is this: lines.set(k, replaceString) -> can I also declare this as public void replaceString??? or is this the easier way?
here we are replacing the indexed(k) value in the arraylist(lines)
that contains the input file values, with the user enterd value.
And also, may I ask, what is the use of byte[], is it like charAt[] or more like Tokenizer?
now the replaced content is writing back to the file. For this we are
converting the string value to the byte array(byte []) and writing
using the FileOutputStream
SOLVED!!! Thanks for the hand guys got it working. Appreciate it!
I'm writing a program that has user name and password input. I am trying to check if a file exists for a user if the user puts in a user name that already exists when they create a user name and password.
The .exists method isn't working and I cant figure it out. Error cannot find symbol comes back. I've changed things, moved things around and got it down to one error. Tried using loops as well as if statements but using if gets me to only one error .Any help would be great.
import java.util.Scanner;
import java.io.*;
class UserData
{
public static void main ( String[] args ) throws IOException
{
Scanner kb = new Scanner(System.in);
System.out.println("Do you have an account? Yes or No: ");
String answer = kb.next().trim();
if ((answer.startsWith("N")) || (answer.startsWith("n")))
{
System.out.println("Create user name: ");
String user = kb.next().trim();
String fileName = user + ".txt";
FileWriter userData = new FileWriter(fileName);
if (userData.exists())
{
System.out.println("User already exists");
System.out.println("Create user name: ");
user = kb.next().trim();
fileName = user + ".txt";
userData = new FileWriter(fileName);
}
System.out.println("Create Password: ");
String ps = kb.next().trim();
userData.write(user + " ");
userData.write(ps);
userData.close();
}
else if ((answer.startsWith("Y")) || (answer.startsWith("y")))
{
System.out.println("Enter user name: ");
String user = kb.next().trim();
System.out.println("Enter Password: ");
String ps = kb.next().trim();
String fileName = user + ".txt";
Scanner inFile = new Scanner(new File(fileName));
String userName = inFile.next();
String password = inFile.next();
// If ((userName != user) || (password != ps))
// {
// System.out.println("User Not Found");
// System.out.println("Enter user name: ");
// String user = kb.next().trim();
//
// System.out.println("Enter Password: ");
// String ps = kb.next().trim();
//
// String fileName = user + ".txt";
// Scanner inFile = new Scanner(new File(fileName));
//
// String userName = inFile.next();
// String password = inFile.next();
// }
// else
// {
System.out.println("User Found");
// }
}
}}
You have compilation error here:
FileWriter userData = new FileWriter(fileName);
if (userData.exists())
Change it to:
File userDataFile = new File(fileName);
if (userDataFile.exists())
and of course:
FileWriter userData = new FileWriter(userDataFile);
userData.write(user + " ");
userData.write(ps);
userData.close();
If file doesn't exist anyway, you might be looking in a wrong directory. Try to add this:
System.out.println(new File(fileName).getAbsolutePath());
And check yourself if the file available on the printed path.