second buffered writer won't work - java

I have a little problem with my simple I/O inventory program. It's a program that writes the output that the user entered into a text file that serves as an "inventory". I was able to do it. However, when I tried to create and append on a different text file on the same file folder, it wouldn't write the input into the new text file. I know I really lack the experience to explain properly my concern. But I'm trying my best though, so basically, I would just like to print the information I entered as "sales" into the second text.file on the same path folder. I hope you can get some ideas if you check and run my code. The code is working but, like I said, the only problem is the input/output on a different text file. I would really appreciate your help. Thanks.
Carl
Here's my code:
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.*;
import static java.nio.file.StandardOpenOption.*;
import java.text.*;
import java.util.*;
public class Inventorypos {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String File ="D:\\Copro2\\Inventory.txt";
String File2 ="D:\\Copro2\\Sales.txt";
Path file = Paths.get("D:\\Copro2\\Inventory.txt");
Path salefile = Paths.get("D:\\Copro2\\Sales.txt");
String st = " ";
String sH = " ";
String sF = " ";
String sS = " ";
String delimeter = "................ ";
int itemnum;
int itemname;
String H="Hamburger";
String F="French Fries";
String S="Softdrinks";
int menu;
long menu2 = 0;
final long QUIT = 5;{
{
try{
Runtime rt=Runtime.getRuntime();
OutputStream invent = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
BufferedWriter writer = new
BufferedWriter(new OutputStreamWriter(invent));
//so here is my problem here, I couldn't make this work
OutputStream sale = new BufferedOutputStream(Files.newOutputStream(salefile, CREATE,StandardOpenOption.APPEND));
BufferedWriter writer2 = new
BufferedWriter(new OutputStreamWriter(sale));
String sa= "---- Sales ----";
writer2.write(sa);
writer2.newLine();
String in= "---- Inventory ----";
writer.write(in);
writer.newLine();
System.out.println("---- Page Menu ----");
System.out.println("1. Add Inventory \n2. Sell \n3. View Inventory \n4. View Sales \n5. Exit ");
System.out.print("Enter selection: ");
menu= input.nextInt();
while(menu2 != QUIT){
if(menu==1) {
System.out.println("Add Inventory: " );
System.out.print("1.) Hamburger \n2.)French Fries \n3.)Softdrinks\n");
System.out.println("Enter Item: " );
itemname= input.nextInt();
if (itemname == 1){
System.out.print("How many do you want to store? ");
itemnum = input.nextInt();
sH = H + delimeter + itemnum;
writer.write(sH, 0, sH.length());
writer.newLine();
}
else if (itemname == 2){
System.out.print("How many do you want to store? ");
itemnum = input.nextInt();
sF = F + delimeter + itemnum;
writer.write(sF, 0, sF.length());
writer.newLine();
}
else if (itemname == 3){
System.out.print("How many do you want to store? ");
itemnum = input.nextInt();
sS = S + delimeter + itemnum;
writer.write(sS, 0, sS.length());
writer.newLine();
}
else{
System.out.println("Invalid input!");
menu=1;
}
System.out.print("Enter 1 to store another item, 2 to view inventory, 3 sell,4 to quit: ");
menu2 = input.nextLong();
if (menu2==1){
menu=1;
}
else if (menu2==2){
menu=3;
}
else if (menu2==3){
menu=6;
}
else if (menu2==4){
menu2=QUIT;
}
else{
System.out.println("Invalid Input!");
}
}
if(menu==2){
System.out.print("---- Food Menu ----");
System.out.println("\n1.) Hamburger P25 \n2.) French Fries P25 \n3.) Softdrinks P25");
System.out.println("Enter your order: ");
int ord = input.nextInt();
if (ord==1){
System.out.println("How many?");
int hm = input.nextInt();
int totph = hm*25;
/*String intwo = "---- Updated inventory ----";
writer.write(intwo);
writer.newLine();
/*int left =
String nI = H+delimeter+*/
st = H+hm+ delimeter+ totph;
writer2.write(st,0,st.length());
writer2.newLine();
System.out.println("You purchased "+hm+" "+H+"s with the total price of "+totph+".");
}
else if (ord==2){
System.out.println("How many?");
int hm = input.nextInt();
int totph = hm*25;
/*String intwo = "---- Updated inventory ----";
writer.write(intwo);
writer.newLine();
/*int left =
String nI = H+delimeter+*/
st = F + hm + delimeter + totph;
writer2.write(st, 0, st.length());
writer2.newLine();
System.out.println("You purchased "+hm+" "+F+" with the total price of "+totph+".");
}
else if (ord==3){
System.out.println("How many?");
int hm = input.nextInt();
int totph = hm*25;
/*String intwo = "---- Updated inventory ----";
writer.write(intwo);
writer.newLine();
/*int left =
String nI = H+delimeter+*/
st = S+hm+ delimeter+ totph;
writer2.write(st,0,st.length());
writer2.newLine();
System.out.println("You purchased "+hm+" "+S+"s with the total price of "+totph+".");
}
else{
System.out.println("Invalid input!");
menu=2;
}
System.out.print("Enter 1 to go back to the food menu, 2 to view sales, 3 to go back to the main option or 4 to quit: ");
menu2 = input.nextInt();
if (menu2==1){
menu=2;
}
else if (menu2==2){
menu=4;
}else if (menu2==4){
menu2=QUIT;
}
else if (menu2==3){
menu=6;
}
else{
System.out.println("Invalid Input!");
}
}
if(menu==3){
{
menu2 = QUIT;
writer.close();
Process p=rt.exec("notepad "+File);
System.out.println("Do you want to continue? y for yes, n for no");
String con = input.next();
if (con.equalsIgnoreCase("y")){
main(null);
}
else if(con.equalsIgnoreCase("n")){
menu2=QUIT;
}
}
}
if (menu==4){
{
menu2 = QUIT;
writer.close();
Process p=rt.exec("notepad "+File2);
System.out.println("Do you want to continue? y for yes, n for no");
String con = input.next();
if (con.equalsIgnoreCase("y")){
main(null);
}
else if(con.equalsIgnoreCase("n")){
menu2=QUIT;
}
}
}
if (menu==5){
System.exit(0);
}
else if (menu ==6){
main(null);
}
else{
System.out.println("Invalid Input!");
}
}
}catch (Exception e){
System.out.println("Message: " +e);
}
}
}
}
}

That's the special thing about BufferedWriter objects. To improve efficiency, they store information in "buffers" or temporary heaps of information and then when the buffer exceeds a certain size, it "flushes" the data or writes it to the file. Flushing the data is done when the flush() method or close() method is called. In your code, I don't believe you called close() on your writer which you actually do regardless of the type.
You can call it using this:
writer.close();
Or if you simply want to save the data without closing the writer yet, you can call:
writer.flush();

Related

Java CSV printing relevant information in relation to User input

my current code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
public class Menu {
private static final String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
public static void main(String[] args) {
boolean exit = false;
int userInputt;
do {
userInputt = printMenu();
switch(userInputt) {
case 1:
inputLocation();
break;
case 2:
inputType();
break;
case 3:
inputRating();
break;
case 4:
System.out.println("Goodbye!");
exit = true;
break;
default:
System.out.println("Invalid Option.");
break;
}
}
/* an int varible that allows the storing of an integer */
while(userInputt > 4);
}
/* an int varible that allows the storing of an integer */
public static int printMenu () {
int selection;
Scanner sc = new Scanner (System.in);
System.out.println("Welcome to Melbnb!");
System.out.println("------------------------------------------------");
System.out.println("> Select from main menu");
System.out.println("------------------------------------------------");
System.out.println(" 1) Search by location");
System.out.println(" 2) Browse by type of place");
System.out.println(" 3) Filter by rating");
System.out.println(" 4) Exit");
System.out.print("Please Select: ");
selection = sc.nextInt();
return selection;
}
private static char inputLocation() {
Scanner userInput = new Scanner(System.in);
File file = new File("C:/Users/andys/OneDrive/Desktop/Melbnb (2).csv");
String fileData = "";
try (Scanner reader = new Scanner(file)) {
// Read the header line so we don't deal with it again
fileData = reader.nextLine();
System.out.print("Please provide a location: ");
String location1 = userInput.nextLine().trim();
List<String> foundRecords = new ArrayList<>();
boolean found = false;
while (reader.hasNextLine()) {
fileData = reader.nextLine().trim();
// Skip blank lines (if any).
if (fileData.isEmpty()) {
continue;
} String regex = ",";
String[] lineParts = fileData.split(regex);
found = (location1.isEmpty() ||
(lineParts[0].contains(location1) ||
(location1.isEmpty() ||
(lineParts[1].contains(location1)))));
if (found) {
foundRecords.add(fileData);
found = false;
}
}
// Display found records (if any)
System.out.println();
System.out.println("Found Records:");
System.out.println("====================================");
if (foundRecords.isEmpty()) {
System.out.println(" No Records Found!");
}
else {
for (String str : foundRecords) {
System.out.println(str);
}
}
System.out.println("====================================");
}
catch (FileNotFoundException ex) {
}
char userInputt;
do {
userInputt = location();
switch(userInputt) {
case 1:
System.out.println("------------------------------------------------");
break;
case 2:
inputType();
break;
case 3:
inputRating();
break;
case 4:
printMenu();
break;
default:
break;
}
}
while(userInputt > 4);
return userInputt;
}{
}
private static char location() {
// TODO Auto-generated method stub
return 0;
}
private static void inputType() {
System.out.println("------------------------------------------------");
}
private static void inputRating() {
}
/* ---------------------------------- Locations ---------------------------------- */
private static void Southbank() {
int southbankPrice = 42;
int southbankClean = 11;
int southbankService = 10;
double southbankDiscount = 0.05;
Scanner checkIn = new Scanner (System.in);
System.out.println("------------------------------------------------");
System.out.println("> Provide dates");
System.out.println("------------------------------------------------");
System.out.print("Please provide check-in date (dd/mm/yyyy): ");
Date inDate = getInputDate(checkIn);
System.out.print("Please provide checkout date (dd/mm/yyyy): ");
Date outDate = getInputDate(checkIn);
System.out.println("------------------------------------------------");
Scanner pInfo = new Scanner (System.in);
System.out.println("> Provide personal information");
System.out.println("------------------------------------------------");
System.out.print("Please provide your given name: ");
String southName = pInfo.nextLine();
System.out.print("Please provide your surname: ");
String southLast = pInfo.nextLine();
System.out.print("Please provide your email address: ");
String southEmail = pInfo.nextLine();
System.out.print("Please provide number of guests: ");
String southGuest = pInfo.nextLine();
System.out.print("Confirm and pay (Y/N): ");
String southConfirm = pInfo.nextLine();
System.out.println("------------------------------------------------");
System.out.println("> Show property details");
System.out.println("------------------------------------------------");
System.out.printf("%-25s%-20s\n", "Property:","Private room in the heart of Southbank hosted by " + southName);
System.out.printf("%-25s%-20s\n", "Type of place:","Private room");
System.out.printf("%-25s%-20s\n", "Location:","Southbank");
System.out.printf("%-25s%-20s\n", "Rating:","4.5");
System.out.printf("%-25s%-20s\n", "Description:","The apartment is situated in the heart of Southbank with an easy access to shops and cafes. It has a warm and spacious living room with an amazing view of the gardens.");
System.out.printf("%-25s%-20s\n", "Number of guests: ", southGuest);
System.out.printf("%-25s%-20s\n", "Price:", "asd");
System.out.printf("%-25s%-20s\n", "Discounted price:","asd");
System.out.printf("%-25s%-20s\n", "Service fee:","asd");
System.out.printf("%-25s%-20d\n", "Cleaning fee: ", southbankClean );
System.out.printf("%-25s%-20s\n", "Total:","asd");
}
/* ---------------------------------- Date Validation ---------------------------------- */
private static Date getInputDate(final Scanner checkIn) {
try {
return new SimpleDateFormat(DEFAULT_DATE_FORMAT).parse(checkIn.nextLine());
} catch (ParseException ex) {
System.out.println("Invalid Date. Please Try again!");
Southbank();
}
return null;
}
}
The first image is my Desired output
The second is my current output
and the third image is my CSV
My program has a feature which will allow the user to a hotel apartment by inputting a specific location for example 'South', as shown in the screenshots of my current output once the term 'South' gets inputted to prints out all the columns for any fields relating to the search term in the CSV file, However i only want the first column to be printed out. How can i achieve this output?
What can i do to achieve my desired output?
I have tried removing the 'for' statement in the following code and replacing the print element with foundrecords.get(0)

If I want to be able to display the "total sales" within the file "Cart.txt", how would I do that?

I want the Cart.txt file to be able write whatever the total sales are in the file itself. The file right now just says:
3,2,Shoes
3,4,Shirt
2,5,Car
This is the current output:
run:
Enter how many items you are buying
3
Enter the items you are buying, structured as followed
Quantity,Price,Item Name:
3,2,Shoes
3,4,Shirt
2,5,Car
Those values were written to Cart.txt
Sold 3 of Shoes at $2.00 each.
Sold 3 of Shirt at $4.00 each.
Sold 2 of Car at $5.00 each.
Total sales: $28.00
This is the code itself:
package shop;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class Shop
{
public static void main(String[] args)
{
String fileName = "Cart.txt";
PrintWriter outputStream = null;
try
{
outputStream= new PrintWriter (fileName);
}
catch (FileNotFoundException e)
{
System.out.println("Error opening the file "+ fileName);
System.exit(0);
}
System.out.println("Enter how many items you are buying");
Scanner keyboard = new Scanner (System.in);
Scanner intinput = new Scanner (System.in);
int input = intinput.nextInt();
System.out.println("Enter the items you are buying, structured as followed"
+ " \nQuantity,Price,Item Name:");
for(int count=1; count<=input; count++)
{
String line = keyboard.nextLine();
outputStream.println(line);
}
outputStream.close();
System.out.println("Those values were written to "+ fileName);
try
{
Scanner inputStream = new Scanner(new File(fileName));
String line = inputStream.toString();
double total = 0;
for(int count=1; count<=input; count++)
{
line = inputStream.nextLine();
String[] ary = line.split (",");
int quantity = Integer.parseInt (ary[0]);
double price = Double.parseDouble(ary[1]);
String description = ary[2];
System.out.printf("Sold %d of %s at $%1.2f each. \n",
quantity, description, price);
total += quantity * price;
}
System.out.printf("Total sales: $%1.2f\n", total);
inputStream.close();
}
catch (FileNotFoundException e)
{
System.out.println("Cannot find file " + fileName);
}
catch (IOException e)
{
System.out.println("Problem with input file " + fileName);
}
}
}
Perform the following :
Write to the file after calculating the total :
outputStream.println(total);
Close the outputStream after writing the total to the file
EDIT:
Make the following changes in this block of code :
System.out.println("Enter the items you are buying, structured as
followed" + " \nQuantity,Price,Item Name:");
double tot = 0.0;
for (int count = 1; count <= input; count++) {
String line = keyboard.nextLine();
outputStream.println(line);
String[] arr = line.split(",");
tot += (Integer.parseInt(arr[0]) * Double.parseDouble(arr[1]));
}
outputStream.println("Total sales: $" + tot);
outputStream.close();
System.out.println("Those values were written to " + fileName);
Here we calculate the total for all entries and then just write it once to the file.
Output
3,2,Shoes
3,4,Shirt
2,5,Car
Total sales: $28.0
I would keep a running total and then add it in at the end:
Double total = 0;
for(int count=1; count<=input; count++)
{
String line = keyboard.nextLine();
outputStream.println(line);
String[] arr= line.split(",");
total += (Double.parseDouble(arr[0]) * Double.parseDouble(arr[1]));
}
outputStream.println("Total: " + total);

Can't read the numbers and values inside of a file in Java?

First of all excuse my bad typing errors and posting mistakes because I'm new to the site and still learning how use it.
I'm supposed to create a code that asks the user if he wants to deposit or withdraw and then asks him to enter the file name and then uses the info inside to add to the account; anyway this code is about 25% finished and I'm having trouble while testing the code so far, because it doesn't seem to read the file's name after I enter it when it asks me, Do you know what may cause this problem? any suggestions or a feedback?
import java.io.*;
import java.util.*;
public class read {
public static void main(String [] args) throws FileNotFoundException {
Double currentbalance = 500.00;
System.out.println("To deposit enter 1");
System.out.println("To Withdrwawl enter 2");
Scanner depositOrWithdrawl = new Scanner(System.in);
int choose = depositOrWithdrawl.nextInt();
if(choose == 1) {
double currentBalance = 500.00;
System.out.println("your current balance is: $"+ currentBalance);
System.out.println("Please enter the file name to deposit: ");
Scanner deposit = new Scanner(System.in);
String depositAmount = deposit.nextLine();
File depositFile = new File(depositAmount);
int nextLine = 1;
while(deposit.hasNextLine()){
double numbers = deposit.nextDouble();
System.out.println("You are about to add: $"+ numbers + " To your Balance");
currentBalance = currentBalance + numbers;
System.out.println("Your current balance is: $" + currentBalance);
nextLine++;
}
}
}
}
By the way it will be very helpful if you tell me how to include the first few lines of the code to use stackoverflow properly
I am guessing that you want to read the file, but you are not doing it anywhere in your program. This line File depositFile = new File(depositAmount); doesn't actually read a file, it only creates a File class object. I strongly suggest you google how to read a file in java. There are plenty of very good tutorials on this subject. Anyways the following code should help you in doing what you are trying to do :-
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
// It is a bad practice to start a Java class name with a lower case character
public class IdentifiableImpl {
public static void main(String[] args) throws FileNotFoundException {
Double currentbalance = 500.00;
System.out.println("To deposit enter 1");
System.out.println("To Withdrwawl enter 2");
Scanner depositOrWithdrawl = new Scanner(System.in);
int choose = depositOrWithdrawl.nextInt();
if (choose == 1) {
double currentBalance = 500.00;
System.out.println("your current balance is: $" + currentBalance);
System.out.println("Please enter the file name to deposit: ");
// Scanner deposit = new Scanner(System.in);
String depositAmount = depositOrWithdrawl.nextLine();
File depositFile = new File(depositAmount);
// Create a stream to read from a file
BufferedReader br = new BufferedReader(new FileReader(depositFile));
// String st;
// int nextLine = 1;
String input;
// Read a file line by line
try {
while ((input = br.readLine()) != null) {
try {
// Convert read line into double
double numbers = Double.valueOf(input);
System.out.println("You are about to add: $" + numbers + " To your Balance");
currentBalance = currentBalance + numbers;
System.out.println("Your current balance is: $" + currentBalance);
// nextLine++;
}
// Handle bad input gracefully
catch (NumberFormatException e) {
System.out.println("Seems like there is an invalid amount in input file." + input
+ " Will not proceed further");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//Close the stream in finally block
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
If you want your loop to scan the file instead of stdin, you need to point the scanner to the file first:
deposit = new Scanner(depositFile);

Loading/reading a .txt file

My last assignment in my intro to Java class asked us to:
Write a console-based (AKA command line based) menu for your user to interact with.
Include the following commands in the menu (you must write code for each):
Input a list of students, use the menu from ArrayDemo: Display, Add, Remove, etc.
Save the list of students to a file using a filename provided by your user
Load the list of students from a file using a filename provided by your user.
I have already done 1-3. How can I get my program to load the info in a .txt file? (Honestly I am not sure if this is what my teacher means when he says loading, because i feel like this may be a bit more complicated than what we have gone over)
I have been able to get my program to open the .txt file with Notepad but I have no idea how to get it to read the whole file and/or save the text info into my program.
import java.util.*;
import java.util.Scanner;
import java.io.*;
public class ArrayDemo_File {
private static Student[] StudentList = new Student[10];
private static FileWriter file;
private static PrintWriter output;
private static FileReader fr;
public static void StudentIndex() {
int index = 0;
while (index < StudentList.length) {
if(StudentList[index] != null) {
System.out.println(index + ": " + StudentList[index].getLName() + ", "
+ StudentList[index].getFName());
}
else {
return;
}
index++;
}
}
// View detailed data for Students listed in the index
public static void IndexData() {
int index = 0;
while (index < StudentList.length) {
if(StudentList[index] !=null) {
System.out.println(index + ": " + StudentList[index].getLName() + ", " + StudentList[index].getFName());
System.out.println("A Number: \t" + StudentList[index].getANum());
System.out.println("Address: \t" + StudentList[index].getAddress());
System.out.println();
}
else {
return;
}
index++;
}
}
// ADD STUDENT
public static void AddStudent() throws IOException {
// Memory
Student student = new Student();
Address address = new Address();
Scanner kb = new Scanner(System.in);
String last;
String frst;
int num;
int house;
String Street;
String City;
String State;
int Zip;
String Line2;
// Student Name and ID
System.out.println();
System.out.print("Last Name:\t");
last = kb.nextLine();
System.out.println();
System.out.print("First Name:\t");
frst = kb.nextLine();
System.out.println();
System.out.print("A Number:\tA");
num = kb.nextInt();
//Address
System.out.println();
System.out.print("What is your house number?\t");
house = kb.nextInt();
kb.nextLine();
System.out.println();
System.out.print("What is your Street's name?\t");
Street = kb.nextLine();
System.out.println();
System.out.print("What is your city?\t");
City = kb.nextLine();
System.out.println();
System.out.print("What is your State?\t");
State = kb.nextLine();
System.out.println();
System.out.print("What is your zip code?\t");
Zip = kb.nextInt();
kb.nextLine();
System.out.println();
System.out.print("Line 2: \t");
Line2 = kb.nextLine();
System.out.println("");
// Processing
address = new Address( house, Street, City, State, Zip, Line2 );
student = new Student(last, frst, num, address);
int index = 0;
while( index < StudentList.length ) {
if( StudentList[index] == null ) break;
index++;
}
StudentList[index] = student;
}
// REMOVE STUDENT
public static void RemoveStudent() {
System.out.println("Remove student");
int index = 0;
while (index < StudentList.length) {
if (StudentList[index] !=null) {
System.out.println(index + ": " + StudentList[index].getLName() + " " + StudentList[index].getFName());
}
index++;
}
Scanner kb = new Scanner(System.in);
int response;
System.out.println(" Please enter student number to remove or -1 to cancel removal");
System.out.print("\nInput: ");
response = Integer.parseInt(kb.nextLine());
if (response != -1) {
StudentList[response] = null;
}
Student[] StudentListTemp = new Student[10];
int nulls = 0;
for(int x = 0; x < StudentList.length; x++) {
if (StudentList[x] == null) {
nulls++;
}
else {
StudentListTemp[x - nulls] = StudentList[x];
}
}
StudentList = StudentListTemp;
}
public static void WriteFile() throws IOException {
String fileName;
Scanner kb = new Scanner(System.in);
System.out.println("Please enter a name for your file: ");
fileName = kb.nextLine();
output = new PrintWriter(fileName + ".txt");
for( int x = 0; x < StudentList.length; x++ ) {
if( StudentList[x] == null )
continue;
output.println( "[" + x + "]" );
output.println( StudentList[x].getFName() );
output.println( StudentList[x].getLName() );
output.println( StudentList[x].getAddress() );
}
output.close();
System.out.println("\n\tFile saved successfully!");
}
public static void loadFile() throws IOException {
Student student = new Student();
String fileName;
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the name of the file: ");
fileName = kb.nextLine();
File file = new File(fileName + ".txt");
if(!file.exists()) {
System.err.println("\n\tError(404)): File Not Found!");
}
else {
System.out.println("\n\tFile found! It will now open!");
//FileReader fr = new FileReader(fileName + ".txt");
//System.out.println(fr);
ProcessBuilder pb = new ProcessBuilder("Notepad.exe", fileName + ".txt");
pb.start();
}
}
//CONSOLE MENU
public static void Menu() throws IOException {
Scanner kb = new Scanner(System.in);
int response;
boolean run = true;
while(run) {
System.out.println("--------------------------" );
System.out.println(" OPTIONS: ");
System.out.println(" 0) View Student Names ");
System.out.println(" 1) View Student details ");
System.out.println(" 2) Add Student ");
System.out.println(" 3) Remove Student ");
System.out.println(" 4) Save to File ");
System.out.println(" 5) Load File ");
System.out.println(" 6) Close Program ");
System.out.println("-------------------------- ");
System.out.print(" Choose an option: ");
response = Integer.parseInt(kb.nextLine());
System.out.println();
switch(response) {
case 0:
StudentIndex();
break;
case 1:
IndexData();
break;
case 2:
AddStudent();
break;
case 3:
RemoveStudent();
break;
case 4:
WriteFile();
break;
case 5:
loadFile();
break;
case 6:
run = false;
break;
default:
System.out.println(" ERROR: "+ response + " ! ");
}
}
System.out.println( "Have a nice day!" );
}
public static void main(String[] args) throws IOException {
// StudentList[0] = new Student("Doe", "Jon", 0000, new Address(00, "Road", "City", "State", 37343, "000"));
// StudentList[1] = new Student("Ricketts", "Caleb", 0001, new Address(000, "000", "000", "0000", 000, "000"));
// StudentList[2] = new Student("Smith", "Amanda", 2222, new Address(000, "000", "000", "000", 000, "000"));
// StudentList[3] = new Student("Wilson", "Judy", 3333, new Address(000, "000", "000", "000", 000, "000"));
Menu();
}
}
I tried using the filereader to read the file but it doesn't output anything. Not sure what I am doing wrong.
Use these code you can write a text file in SDCard along with you need to set permission in android manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
before writing files also check whether your SDCard is Mounted & your external storage state is writable
Environment.getExternalStorageState()
Cod:
public void generateNoteOnSD(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}
}
Check the http://developer.android.com/guide/topics/data/data-storage.html
Scanner does a good job of reading .txt files. Use another Scanner object to read through the file, one line at a time. After the code completes, each line of the file will be stored in list, with each line at the corresponding index (ex: list.get(0) will return the first line, list.get(1) the second, etc).
public static void loadFile()
{
Student student = new Student();
String fileName;
Scanner kb = new Scanner(System.in);
Scanner read;
ArrayList<String> list = new ArrayList<String>();
System.out.println("Please enter the name of the file: ");
fileName = kb.nextLine();
File file = new File(fileName + ".txt");
if(!file.exists())
{
System.err.println("\n\tError(404)): File Not Found!");
} else {
System.out.println("\n\tFile found! It will now open!");
read = new Scanner(file);
//FileReader fr = new FileReader(fileName + ".txt");
//System.out.println(fr);
//ProcessBuilder pb = new ProcessBuilder("Notepad.exe", fileName + ".txt");
//pb.start();
while(read.hasNextLine()) {
String currentLine = read.nextLine();
list.add(currentLine);
}
}
}

Updating a double in a text file

I have an ArrayList with user accounts stored into a text file, each account represents a virtual bank account.
What is the most efficient way for me to update the balance of an account, after a user decides to add, or withdraw money?
I have successfully retrieved the balance, just need to save it.
Here is what I have so far, most of the magic happens in the ATM and Bank classes
ATM CLASS
public class ATM {
public static void main(String[] args) throws IOException {
Bank bank = new Bank();
double balance = 0;
// Welcome screen
String dash = "-------------------\n";
System.out.print(dash);
System.out.print("Welcome to the Bank\n");
System.out.print(dash);
System.out.println("Do you have an account with us? (y/n) ");
Scanner scanner = new Scanner(System.in);
String answer = scanner.nextLine();
while (true) {
if (answer.equalsIgnoreCase("y")) {
System.out.println("Username: ");
String userName = scanner.next();
System.out.println("PIN: ");
int pin = scanner.nextInt();
bank.hasUser(userName, pin);
if (bank.hasUser(userName, pin)) {
User.balance = bank.getBalance(userName, pin, balance);
bank.menu();
break;
} else if (!bank.hasUser(userName, pin)) {
System.out.println("\n** Incorrect username or password, please try again**\n");
}
} else if (answer.equalsIgnoreCase("n")) {
Bank.newUser();
break;
} else {
System.out.println("\nThat's not an option, do you have an account with us?");
}
}
}
}
BANK CLASS
public class Bank {
public static void newUser() {
// new user is created
String dash = "-------------------\n";
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your full name below (e.g. John M Smith): ");
String name = scanner.nextLine();
System.out.println("Create a username: ");
String userName = scanner.nextLine();
System.out.println("Enter your starting deposit amount: ");
double balance = scanner.nextDouble();
System.out.print(dash);
System.out.print("Generating your information...\n");
System.out.print(dash);
int pin = PIN();
String accountNum = Bank.accountNum();
User user = new User(name, userName, pin, accountNum, balance);
// new user gets added to the array list
Bank.users.add(user);
try {
File file = new File("users.text");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.append(String.valueOf(Bank.users + "\n"));
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void menu() {
while (true) {
System.out.print("\n1");
System.out.print(" - Acount Summary ");
System.out.print("3");
System.out.print(" - Deposit Money\n");
System.out.print("2");
System.out.print(" - Withdraw Money ");
System.out.print("4");
System.out.print(" - Exit\n\n");
System.out.print("I would like to: \n");
Scanner bscanner = new Scanner(System.in);
int mc = bscanner.nextInt();
if (mc == 1) {
System.out.print("Your current balance is: $"
+ User.getBalance() + "\n");
} else if (mc == 2) {
System.out.print("Enter withdrawl amount: ");
double wd = bscanner.nextDouble();
User.balance -= wd;
System.out.println("\n$" + User.getBalance()
+ " is your new account balance.");
} else if (mc == 3) {
System.out.print("Enter deposit amount: ");
double dp = bscanner.nextDouble();
User.balance += dp;
System.out.println("\n$" + User.getBalance()
+ " is your new account balance.");
} else if (mc == 4) {
System.exit(0);
} else {
System.out
.print("\nThat's not an option, please select an option listed below!\n");
}
}
}
public boolean hasUser(String userName, int pin) {
try {
BufferedReader reader = new BufferedReader(new FileReader(
"users.text"));
String line;
while ((line = reader.readLine()) != null) {
line = line.replaceAll("[\\[\\]]", "");
String[] tokens = line.split(",");
if (userName.equals(tokens[1])
&& pin == Integer.parseInt(tokens[3])) {
return true;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
public double getBalance(String userName, int pin, double balance) {
boolean r = false;
try {
BufferedReader br = new BufferedReader(new FileReader("users.text"));
String line;
while ((line = br.readLine())!= null) {
line = line.replaceAll("[\\[\\]]", "");
String[] num = line.split(",");
if (userName.equals(num[1]) && pin == Integer.parseInt(num[3])) {
r = true;
}
if (r) {
balance = Double.parseDouble(num[4]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return balance;
}
// array list for users
static ArrayList users = new ArrayList();
{
};
}
A good way to do this would be to keep the accounts in ArrayList (as you are doing) and then just save the whole text file again. If you are dealing with small amounts of data it would not take very long. (A better way to think about optimizing is not re-opening the file every time you need to access it's data, just keep it in an array list).
Also, you may not need to save the file after every change. If you are the only app using the file try just saving it when you get closed.
If you want really good performance you will need a data base.
You have to write to the file i dont see any of that...
File fileWriter = new File("user.txt"); //recall it or whatever
PrintWriter writer = new PrintWriter(new FileWriter(fileWriter, true)); //APPEND
writer.println(balance, name, eg...);
writer.close();
}
Printwriter is more effective than filewriter, and filewriter is needed anyhow but this will work, also if you want to do multiples people then just for loop it, and dont forget to close!
for (int i = 0; i < users; i++) { //the for loop
if you still have issues then ask again i've done dbms and the other answer is wayyy off. Hope this helps!

Categories

Resources