How to edit a txt file using PrintWriter? - java

I have the following java file that stores student data (a student number and their surname) in a txt file:
import java.util.*;
import java.io.*;
public class Students {
static Student[] studentArray = new Student[100];
static int currentStudents = 0;
Scanner console = new Scanner(System.in);
File log = new File("log.txt");
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(log, true)));
Scanner input = new Scanner(log);
public static void main(String[] args) {
String logNo;
String logSurname;
if(!(input.hasNextLine())) {
System.out.println("No student data has been loaded.")
}
while(input.hasNextLine()) {
logNo = input.next();
logSurname = input.next();
addStudent(logNo, logSurname);
input.nextLine();
}
String number;
String surname;
System.out.println("Please input details:");
System.out.printf("\n");
System.out.println("Student number: ");
number = console.nextLine();
System.out.println("Student surname: ");
surname = console.nextLine();
output.println(number+"\t"+surname);
addStudent(number, surname);
editSurname();
output.close();
}
public static void addStudent(String number, String surname) {
studentArray[currentStudents] = new Student(number, surname);
}
public static void editSurname() {
String newSurname;
System.out.println("Please input student number:");
// find student with inputted student number
System.out.println("Please enter new surname");
// set surname to another using Student method
}
}
Upon opening, the code reads in any text in the .txt file and constructs Student objects as required, so that the state of the system persists everytime the code runs.
However, I'm struggling to find a way to edit the .txt file using PrintWriter when I call my editSurname() function. How would I go about isolating the student with a specific student number and then edit the required field?

Use a csv file instead of a txt file. Use OpenCSV to process the records.
OR
Have your txt file 1 record per line.
Separate each field by separator.
Create another temporary text file in memory.
Modify the records and save the records in the temporary file.
Delete the original file.
Rename the temporary file with original file name.
For editing your student record, you need to first read all the records in memory.
Create an array of student objects to hold all the records. Perform a binary search on the
objects and modify them.

Why should not use Database concept, It is easily done with Database

Related

Program freezes during run at While loop

The program I am writing needs to read 4 lines of data from a text file containing an ID, Name, Level, and Salary for an employee. It then needs to create a formatted email address and print all of this to standard output. The text file can contain an unknown number of employees, so a while loop must be used with the hasNext() method to confirm there is more data to read.
My program freezes (using Dr. Java) as soon as the while loop begins, and I cant figure out why.
Here is my code so far
public static void main(String[] args) throws IOException {
File file = new File("employeeInput.txt");
if (file.exists()) { //check if file exists
Scanner inputFile = new Scanner(file); //opens file
String companyName = inputFile.nextLine();
System.out.println(companyName);
System.out.println();
System.out.println("----------------------------");
while (inputFile.hasNext()); {
String studentID = inputFile.nextLine();
System.out.println(studentID);
String studentName = inputFile.nextLine();
System.out.println(studentName);
String employeeLevel = inputFile.nextLine();
System.out.println(employeeLevel);
double salary = inputFile.nextDouble();
System.out.println(salary);
}
inputFile.close();
}
else {
System.out.println("The file employeeInput.txt does not exist");
}
}
}
I understand this code is not complete and does everything the program needs to, but I do not get why it's freezing at the while loop..
Any help or advice would be appreciated. This is my first class ever in programming language, so go easy on me :)

How to convert a text file to array object? Java

I am working on a program that takes in a text file and converts it to a team roster. The text file has unknown length, first name, last name, offence score, and defense score. the name and scores are on the same line. Rachael Adams 3.36 1.93. I can not figure out how to convert each line of the text file into an object. I've searched the internet and all of the examples just have one value per a line and converts it into one big array. I've included some extra imports in the code because i know that I will need them further on in the project(find best attackers, best defenders, make teams of 6, print teams). I've modified code from previous projects that took in numbers separated by lines.
class VolleyballFile {
String fileName;
int count;
String currentFileName;
String outputFile="";
String firstName;
String lastName;
double attackScore;
double defenceScore;
Scanner input = new Scanner(System.in);
public VolleyballFile() throws FileNotFoundException {
System.out.println("Please enter a file name to get the roster from");
this.fileName = input.nextLine();
File file = new File(fileName);
Scanner scan = new Scanner(file);
while (scan.hasNextLine()){
int result = Integer.parseInt(scan.nextLine());
this.count+=1;
}
}
}
Using the command String.split(); you can split a string up to an array of strings. So:
while (scan.hasNextLine()) {
//int result = Integer.parseInt(scan.nextLine());
string[] line = scan.nextLine().split(" ");
firstName = string[0];
lastName = string[1];
attackScore = Float.Parse(string[2]);
defenceScore = Float.Parse(string[3]);
this.count+=1;
}
I'm not sure if you can Float.Parse(), don't remember since I haven't used java recently.

How to name a file using variable and returning the filename

My objective is to create a method in which a user inputs their first name and last name, and with this information a .txt file will be created and named using the first initial of the first name and the last name. For example if user enter Marcus Simmon, the text file created should be named "MSimmon.txt" and how would I be able to return this file name. Thank you in advance. This is my code so far...
public static String GetUserInfo() {
// complete with your code of the method GetUserInfo
Scanner input = new Scanner(System.in);
System.out.println("Please enter your first name: ");
char initial = input.next().charAt(0);
System.out.println("Please enter your last name: ");
String lastName = input.nextLine();
try{
FileWriter x = new FileWriter(initial + lastName + ".txt");
}
catch(IOException e){
System.out.println("ERROR");
}
}

Trouble while moving a data from one to another using File Handling in Java

To provide some context, I am writing code in Java to move data from one file to another using File Handling. The files are named in the following format: "form+stream.txt". The form is equivalent to a student's grade, so for instance if he is grade-12 then his form is SC, whereas the Stream is equivalent to section, which could be 1,2,3,4 or 5. So if a student is in grade-11 and section 5, his data will be stored in a file named "S5.txt". The following code shows all the variables of the Student Class:
class Student
{
public int school_number;
String surname;
String first_name;
String current_board;
String form;
int stream;
String house;
int late_mark;
int absent_mark;
int present_mark;
//methods of Student class
}
This information is stored in a Text file in the following format:
School Number
First Name
Surname
Current Board
Form
Stream
House
Late Mark
Absent Mark
Present Mark
Now suppose I want to change the Form of any particular student, I can easily do that by creating another Text File. However, the problem in this case is that by changing the form of the student I would have to move him to another file because if you recall, I mentioned that the Students are added to files according to their stream/section and Form. Therefore I would have to first delete the student from the existing file and add him to a file, which is based on a new combination of his form and stream. To do this I used the following code:
System.out.println("Welcome");
System.out.println();
System.out.println("Please enter the School Number of the Student whose Information you would like to change");//Since school number is Unique
int x=Integer.parseInt(bw.readLine());
int test=0;
for(int i=0;i<30;i++)
for(int j=0;j<100;j++)
{ if(a[i][j]!=null)
// This array is reads all the student information from the text files and creates objects of student type.
{
if(this.a[i][j].school_number==x)
{
System.out.println("The Previous Entry of the Form was: "+this.a[i][j].form);
System.out.println("Please enter the new Form");
String w=this.bw.readLine();
Student q=new Student();
String num="";
num=num.valueOf(x);
if(w.equals("SC")||w.equals("S")||w.equals("A")||w.equals("B")||w.equals("C")||w.equals("D")) //Checking whether the input is valid or not.
{
//Making Changes to the File
File f=new File("Temp.txt");
f.createNewFile();
String v="";
v=v.valueOf(this.a[i][j].stream);
String u=this.a[i][j].form;
BufferedReader br=new BufferedReader(new FileReader(u+v+".txt")); //Form+Stream as I mentioned earlier
BufferedWriter bw=new BufferedWriter(new FileWriter("Temp.txt"));
String a=br.readLine();
while(a!=null)//Writing Data to Temp File
{ bw.write(a);
bw.newLine();
a=br.readLine();
}
br.close();
bw.close();
BufferedReader br1=new BufferedReader(new FileReader("Temp.txt"));
BufferedWriter bw1=new BufferedWriter(new FileWriter(u+v+".txt"));
String b=br1.readLine();
while(b!=null)
{ if(b.equals(num))// Deleting the student from the previous file
{ bw1.write("*"); //I didn't know what else to write
bw1.newLine();
String z1=br1.readLine();
if(z1.equals(this.a[i][j].first_name))
bw1.write("*");
bw1.newLine();
String z2=br1.readLine();
if(z2.equals(this.a[i][j].surname))
bw1.write("*");
bw1.newLine();
String z3=br1.readLine();
if(z3.equals(this.a[i][j].current_board))
bw1.write("*");
bw1.newLine();
String z4=br1.readLine();
if(z4.equals(this.a[i][j].form))
bw1.write("*");
bw1.newLine();
String z5=br1.readLine();
int q0=Integer.parseInt(z5);
if(q0==this.a[i][j].stream)
bw1.write("*");
bw1.newLine();
String z6=br1.readLine();
if(z6.equals(this.a[i][j].house))
bw1.write("*");
bw1.newLine();
String z7=br1.readLine();
int q1=Integer.parseInt(z7);
if(q1==this.a[i][j].late_mark)
bw1.write("*");
bw1.newLine();
String z8=br1.readLine();
int q2=Integer.parseInt(z8);
if(q2==this.a[i][j].absent_mark)
bw1.write("*");
bw1.newLine();
String z9=br1.readLine();
int q3=Integer.parseInt(z9);
if(q3==this.a[i][j].present_mark)
bw1.write("*");
}
else
bw1.write(b);
bw1.newLine();
b=br1.readLine();
}
bw1.close();
br1.close();
BufferedReader br2=new BufferedReader(new FileReader("Temp.txt"));
String g="";
g=g+w;
int h=this.a[i][j].stream;
String hh="";
hh=hh.valueOf(h);
String new_file=g+hh;
BufferedWriter bw2=new BufferedWriter(new FileWriter(new_file+".txt",true));
String bb=br2.readLine();
while(bb!=null&&!(bb.equals("")))//Adding data to the new File.
{ if(bb.equals(num))
{bw2.newLine();
bw2.write(bb);
bw2.newLine();
String z1=br2.readLine();
if(z1.equals(this.a[i][j].first_name))
bw2.write(z1);
bw2.newLine();
String z2=br2.readLine();
if(z2.equals(this.a[i][j].surname))
bw2.write(z2);
bw2.newLine();
String z3=br2.readLine();
if(z3.equals(this.a[i][j].current_board))
bw2.write(z3);
bw2.newLine();
String z4=br2.readLine();
if(z4.equals(this.a[i][j].form))
bw2.write(w);
bw2.newLine();
String z5=br2.readLine();
int q0=Integer.parseInt(z5);
if(q0==this.a[i][j].stream)
bw2.write(z5);
bw2.newLine();
String z6=br2.readLine();
if(z6.equals(this.a[i][j].house))
bw2.write(z6);
bw2.newLine();
String z7=br2.readLine();
int q1=Integer.parseInt(z7);
if(q1==this.a[i][j].late_mark)
bw2.write(z7);
bw2.newLine();
String z8=br2.readLine();
int q2=Integer.parseInt(z8);
if(q2==this.a[i][j].absent_mark)
bw2.write(z8);
bw2.newLine();
String z9=br2.readLine();
int q3=Integer.parseInt(z9);
if(q3==this.a[i][j].present_mark)
bw2.write(z9);
bb=br2.readLine();
}
else
bb=br2.readLine();
}
bw2.close();
br2.close();
f.delete();
test=1;
}
}
}
}
if(test==1)
System.out.println("Change Successful!");
if(test==0)
{
System.out.println("Student not found in DATABASE. Would you like to add student?");
}
}
}
}
This code is not working properly and is producing erroneous results. The star pattern is appearing on the original file, which I believe is good news, however the last block of the code which deals with writing new data to the file is not working. The new text file, which is supposed to have information is appearing to be blank withs spaces. What mistake have I made? Please help
PS: Sorry for the length of the question and please do tell me if any more information regarding the code is needed.
Thank You.

How to read data from file to create objects?

I'm struggling to figure out how to read the data from a file we've been given and use that to create an instance of an object. We are given a txt file of customer data for a store. It is in the following format:
123.64382392 12 1.1234123419
Each line of the file is like this. The first column is Arrival time, the second is number of items, and the third is the time it takes the customer to find one item. There are about 100 customers in this file and I'm not sure how to read from the file to create all the instances necessary.
public static void loadCustomers(){
File file = new File("origCustomerArrivals.txt");
try{
Scanner input = new Scanner(file);
while (input.hasNextLine())
{
double arrivalTime = input.nextDouble();
int numItems = input.nextInt();
double selectionTime= input.nextDouble();
Customer newCustomer = new Customer(arrivalTime, numItems,selectionTime);
input.nextLine();
}
input.close();
}
catch(FileNotFoundException e){
System.out.println("file not opened");
}
}
}
Try this:
public static void loadCustomers(){
File file = new File("origCustomerArrivals.txt");
try{
List<Customer> list = new ArrayList<Customer>();
Scanner input = new Scanner(file);
while (input.hasNextLine())
{
String[] values = scan.nextLine().split("\\s+");
arrivalTime = Double.parseDouble(values[0]);
numItems = Integer.parseInt(values[1]);
selectionTime = Double.parseDouble(values[2]);
Customer newCustomer = new Customer(arrivalTime, numItems,selectionTime);
list.add(newCustomer);
input.nextLine();
}
input.close();
}
catch(FileNotFoundException e){
System.out.println("file not opened");
}
}
}
Could you elaborate on what part of your code isn't working? I tested it myself (printed out the values instead of creating a new Customer object), and it works fine. Except "input.nextLine();" in the while loop is not necessary. It will already jump to the next line, and once you reach the end of your file that will likely cause an error to be thrown.
Also, once you create the object instance, I assume you'll want to save it to a list of the objects. You can do this by creating an ArrayList of object Customer outside the loop:
ArrayList<Customer> Customers = new ArrayList<Customer>();
Then as each instance is created in the loop, add it to this ArrayList:
Customers.add(newCustomer);

Categories