I've got a text file like this: https://i.stack.imgur.com/nL0Z4.png
The first column represents the user ID and the last column represents balance. I want to iterate through the elements to find a specific user ID and then update their balance. I've managed to match the user ID and access the balance using the Scanner but I'm not sure how to update the balance in the text file with a new value. This is the code I've written so far: I tried to take the elements, modify the balances and put the updated values in an arraylist. Then put them into the text file using PrintWriter. But I keep getting an empty text file when I call this function.
File file = new File("UserInfo.txt");
Scanner sc = new Scanner(file);
ArrayList<String> items = new ArrayList<String>();
while(sc.hasNextLine()){
String info = sc.nextLine();
String data[] = info.split(" ");
if(String.valueOf(currentUser.getAccountNumber()).equals(data[0])){
data[3] = String.valueOf(currentUser.getBorrowBalance());
//Updating the balance in ArrayList
}else{
continue;
}
for(int i=0; i<data.length; i++){
items.add(data[i]);
}
}
PrintWriter pw = new PrintWriter(file);
for(int j=0; j<items.size(); j++) {
pw.printf("%s ", items.get(j));
if(j%3==0) pw.println(); //Going to new line after writing 4 elements to text file
}
pw.close();
sc.close();
I would highly reccomend to use Serialization for this. I am assumming you already have a Customer class with balance,id etc. With Serialization things are just as simple as getting the customer you want,updating his balance,and then writing in your file.For example:
customer = getCustomerById(selectedId);
customer.setBalance(newBalance);
customer.write();
And the write method would look like this
public void write(String filename) {
try {
File temp = new File(filename);
temp.createNewFile(); // create file if not present
FileOutputStream fileOut = new FileOutputStream(filename);
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(this);
} catch (Exception ex) {
ex.printStackTrace();
}
}
More on Serialization here
Related
so I have a text file and i am trying to read line by line and then populate my array list.
a sample text file is shown below:
10,11,11/10/2021,24,1,2
11,12,11/10/2021,1,2,3
12,13,11/10/2021,24,5
13,14,11/10/2021,1,11,32,2
14,15,11/10/2021,1,9,8
I have been able to read in the first 4 elements (ID,ID,date,price)
and then i need to populate the other elements on that line into an array list (all elements after price)
the problem I am having is that it populates all the other lines into the array list and just not the remaining elements for the one line.
here is the code
int ID = 0;
int spareID = 0;
String date = "";
float fee = 0;
ArrayList<String> limits = new ArrayList<String>();
ArrayList<Import> imports= new ArrayList<Imports>();
File myfile = new File("file.txt");
try {
Scanner inputFile = new Scanner(myfile);
inputFile.useDelimiter(",");
// setting comma as delimiter pattern
while (inputFile.hasNextLine()) {
ID = inputFile.nextInt();
SpareID = inputFile.nextInt();
date = inputFile.next();
fee = inputFile.nextFloat();
while (inputFile.hasNext()) {
limits.add(inputFile.next());
}
Import import = new Import(ID, spareID, fee, date, limits);
imports.add(import);
}
inputFile.close();
} catch (FileNotFoundException e) {
System.out.println("error: can not find file");
}
the array list is capturing the rest of the text file when i need it to capture just the remaining elements on that line.
Edit: the first 4 elements of the line will all go into a different variable and then I need the rest or the elements on that line only to go into the array list
Use Scanner.nextLine() to get a single line, then create a second Scanner with that line to parse it contents.
Scanner inputFile = new Scanner(myfile);
while (inputFile.hasNextLine()) {
Scanner line = new Scanner(inputFile.nextLine());
// setting comma as delimiter pattern
line.useDelimiter(",");
ID = line.nextInt();
SpareID = line.nextInt();
date = line.next();
fee = line.nextFloat();
while (line.hasNext()) {
limits.add(line.next());
}
}
inputFile.close();
user input a number ,if i repeat same the number and write the number in my text file. how can i stop the duplication. ?
i create a text file and write numbers in my text file.. if i write same number repeatedly that was write in my file..please correct my code.. i want write a number only one time....
public class FileOp extends Thread {
volatile String s = "yes";
void create() throws InterruptedException, IOException {
String filename = "Numberfile.txt";
File file = new File(filename);
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
if (file.createNewFile()) {
System.out.println("\nFile '" + filename + "' has
been created.\n");
} else {
System.out.println("\nFile '" + filename + "'
already exists.\n");
}
}
void write() throws InterruptedException, IOException {
FileWriter fw = new FileWriter("Numberfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
do {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a number :");
int a = in.nextInt();
bw.write("" + a + "\n");
System.out.println("Succesfully added in
Numberfile");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
System.out.println("Do you want continue
(yes / no) ? ");
s = in.next();
}
while (s.equalsIgnoreCase("yes"));
bw.close();
}
}
i enter a number 2 and it write in my text file,and i enter the number 2 repeatedly .. its store in text file. i don't want that.. only one time it's write in text file,
You don't need set, just make a list of type Integer that contains the previous numbers added. Use list.add(number) to add and list.contains(number) to check if number already exists in the list before writing to file/adding to list.
declaring a list of type integer: List<Integer> numbers = new ArrayList<>();
Also go check out the Collections in java:
Class Collections
edit: set declaration: Set<Integer> set = new HashSet<>();
I am trying to read in a text file and then manipulate a little and update the records into a new text file.
Here is what I have so far:
ArrayList<String> linesList = new ArrayList<>();
BufferedReader br;
String empid, email;
String[] data;
try {
String line;
br = new BufferedReader(new FileReader("file.txt"));
while ((line = br.readLine()) !=null) {
linesList.add(line);
}
br.close();
}
catch (IOException e) { e.printStackTrace(); }
for (int i = 0; i < linesList.size(); i++) {
data = linesList.get(i).split(",");
empid = data[0];
ccode = data[3];
}
File tempFile = new File("File2.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
for (int i = 0; i < linesList.size(); i++) {
if(i==0){
bw.write(linesList.get(i));
bw.newLine();
}
else{
data = linesList.get(i).split(",");
String empid1 = data[0];
if(data[13].equals("IND")) {
String replace = data[3].replaceAll("IND", "IN");
ccode1 = replace;
System.out.println(ccode1);
}
else if(data[13].equals("USA")) {
String replace = data[3].replaceAll("USA", "US");
ccode1 = replace;
}
else {
ccode1 = replace; //This does not work as replace is not defined here, but how can I get it to work here.
}
String newData=empid1+","+ccode1;
bw.write(newData);
bw.newLine();
}
}
Here is what is inside the text file:
EID,First,Last,Country
1,John,Smith,USA
2,Jane,Smith,IND
3,John,Adams,USA
So, what I need help with is editing the three letter country code and replacing it with a 2 letter country code. For example: USA would become US, and IND would become IN. I am able to read in the country code, but am having trouble in changing the value and then replacing the changed value back into a different text file. Any help is appreciated. Thanks in advance.
Open file in text editor, Search and Replace, ,USA with ,US, ,IND with ,IN and so on.
As such, to automate it, on the same while loop you read a line do:
//while(read){ line.replaceAll(",USA",",US");
That will be the easiest way to complete your objective.
To save, open a BufferedWriter bw; just like you opened a reader and use bw.write(). You would probably prefer to open both at the same time, the reader on your source file, and the writer on a new file, with _out suffix. That way you dont need to keep the file data in memory, you can read and write as you loop.
For harder ways, read the csv specs: https://www.rfc-editor.org/rfc/rfc4180#section-2
Notice that you have to account for the possibility of fields being enclosed in quotes, like: "1","John","Smith","USA", which means you also have to replace ,\"USA with ,\"US.
The delimiter may or may not be a comma, you have to make sure yur input will always use the same delimiter, or that you can detect and switch at runtime.
You have to account for the case where a delimiter may be part of a field, or where quotes are part of a field.
Now you know/can solve these issues you can, instead of using replace, parse the lines character by character using while( (/*int*/ c = br.read()) != -1), and do this replacement manually with an if gate.
/*while(read)*/
if( c == delimiter ){
if not field, start next field, else add to field value
} else if( c == quote ){
if field value empty, ignore and expect closing quote, else if quote escape not marked, mark it, else, add quote to field value
}
(...)
} else if( c == 13 or c == 10 ){
finished line, check last field of row read and replace data
}
To make it better/harder, define a parsing state machine, put the states into an Enum, and write the if gates with them in mind (this will make your code be more like a compiler parser).
You can find parsing code at different stages here: https://www.mkyong.com/java/how-to-read-and-parse-csv-file-in-java/
You need to change a little bit in your concept. If you want to edit a file then,
create a new file and write content in new file and delete old file and rename new file
with old name.
ArrayList<String> linesList = new ArrayList<>();
BufferedReader br;
String[] data;
File original=new File("D:\\abc\\file.txt");
try {
String line;
br = new BufferedReader(new FileReader(original));
while ((line = br.readLine()) !=null) {
linesList.add(line);
}
br.close();
}
catch (IOException e) { e.printStackTrace(); }
File tempFile = new File("D:\\abc\\tempfile.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
for (int i = 0; i < linesList.size(); i++) {
if(i==0){
bw.write(linesList.get(i));
bw.newLine();
}
else{
data = linesList.get(i).split(",");
String empid = data[0];
String name=data[1];
String lname=data[2];
String ccode = data[3].substring(0, 2);
String newData=empid+","+name+","+lname+","+ccode+"\n";
bw.write(newData);
bw.newLine();
}
}
bw.close();
if (!original.delete()) {
System.out.println("Could not delete file");
return;
}
// Rename the new file to the filename the original file had.
if (!tempFile.renameTo(original))
System.out.println("Could not rename file");
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);
i got 2 functions which i created 1 is to change Password and 1 to delete the file. so my intention is to run the change password feature first followed by doing the delete file. the code runs properly and creates the new password in a new file. but it does not work when trying to delete the file & renaming need some help pls
public static void replaceAdminPassword()throws IOException{
try {
Scanner read = new Scanner(System.in);
System.out.println("Enter Old Password: ");
String oldPass = read.nextLine();
String UserPHash = Utility.getHash(oldPass);
System.out.println("Enter New Password: ");
String newPass = read.nextLine();
String UserNHash = Utility.getHash(newPass);
read = new Scanner(new File("admin.dat"));
String line;
String[] details;
String input = "";
File fout = new File("out.dat");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
while (read.hasNextLine()){
line = read.nextLine();
details = line.split("\\|");
if(details[0].equalsIgnoreCase(UserPHash)){
input = UserNHash;
bw.write(input);
System.out.println("Password Changed.");
}
}
bw.close();
replaceAdminFile();
}catch (FileNotFoundException ex){
System.out.println("file not found");
}
}
public static void replaceAdminFile(){
File oldFile = new File("admin.dat");
File newFile = new File("out.dat");
oldFile.delete();
newFile.renameTo(oldFile);
}
I would recommend to use new io API instead :
Files.delete(Paths.get("admin.dat"));
Files.move(Paths.get("out.dat"), Paths.get("admin.dat"));
You might want to check the documentation of move and delete.
Don't forget to import java.nio.file.Files and java.nio.file.Paths.
You need to close the Scanner by calling "read.close()" otherwise the file is still open and you can't rename or delete it.