Read empty line in text file - java

if I want to read file from text file and store it in an array,each line goes to correct array
this is the text file
111111,34,24.5,first line
222222,53,22.0,second line
333333,,32.0,third line
44444,22,12.6,
if line is empty through exception saying "title is missing" or something like that.
a code has been made if the array length==4 then display lines in order but if length less than 4 and line is missing throw exception but when I want to put last array[3] gives me error. have a look if you can seethe error that would help
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Itry {
public static void main(String[] args) {
// TODO Auto-generated method stub
String [] splitArray = new String[4];
String line = "";
String array1, description;
int number;
double price;
// Total sales
double total = 0;
Scanner keyboard = new Scanner (System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
Scanner fileReader = null;
try {
File Fileobject = new File (filename);
fileReader = new Scanner (Fileobject);
System.out.println("\nTransactions");
System.out.println("================");
while(fileReader.hasNext())
{
// Contains stock code,Quantity,Price,Description
line = fileReader.nextLine();// Read a line of data from text file
splitArray = line.split(",");
// check to make sure there are 4 parts in splitArray
if(splitArray.length == 4)
{
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
// Extract each item into an appropriate
// variable
try {
array1 = splitArray[0];
number = Integer.parseInt(splitArray[1]);
price = Double.parseDouble(splitArray[2]);
description = splitArray[3];
// Output item
System.out.println("Sold "+String.format("%-5d", number) +
String.format("%-12s", description )+ " at "+"£"+
String.format("%-5.2f", price));
// Compute total
total += number * price;
} // end of try
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}
} //end of if
else if (splitArray[0].length()<1) {
try { splitArray[0] = splitArray[0].trim();
System.out.println(" Title is missing "+" "+splitArray[1] +""+splitArray[2]+"");
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}
}
else if (splitArray[1].length()<=1) {
try { splitArray[1] = splitArray[1].trim();
System.out.println(splitArray[0]+" "+" here is missing " +""+splitArray[2] );
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
else if (splitArray[2].length()<=1) {
try { splitArray[2] = splitArray[2].trim();
System.out.println(splitArray[0]+" "+splitArray[1] +""+" here is missing "+splitArray[3]);
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
else if (splitArray[3].length()<=1) {
try { splitArray[3] = splitArray[3].trim();
System.out.println(splitArray[0]+" "+splitArray[1] +""+splitArray[2]+"title is missing");
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
}//end of while
System.out.printf("\nTotal sales: £"+String.format("%-6.2f", total));
}// end of try block
catch (FileNotFoundException e)
{
System.out.println("Error - File does not exist");
}
}
}

You can do it as follows:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] splitArray = new String[4];
String line = "";
String array1, description;
int number;
double price;
// Total sales
double total = 0;
Scanner keyboard = new Scanner(System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
Scanner fileReader = null;
try {
File Fileobject = new File(filename);
fileReader = new Scanner(Fileobject);
System.out.println("\nTransactions");
System.out.println("================");
int count = 1;
while (fileReader.hasNext()) {
// Contains stock code,Quantity,Price,Description
line = fileReader.nextLine();// Read a line of data from text file
try {
if (line != null && line.length() > 0) {
splitArray = line.split(",");
// check to make sure there are 4 parts in splitArray
if (splitArray.length == 4) {
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
// Extract each item into an appropriate variable
try {
array1 = splitArray[0];
number = Integer.parseInt(splitArray[1]);
price = Double.parseDouble(splitArray[2]);
description = splitArray[3];
// Output item
System.out.println(
"Sold " + String.format("%-5d", number) + String.format("%-12s", description)
+ " at " + "£" + String.format("%-5.2f", price));
// Compute total
total += number * price;
} catch (NumberFormatException e) {
System.out.println("Error in line#" + count + ": insufficient/invalid data");
}
} else {
throw new IllegalArgumentException(
"Error in line#" + count + ": insufficient/invalid data");
}
} else {
throw new IllegalArgumentException("Line#" + count + " is empty");
}
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
count++;
} // end of while
System.out.printf("\nTotal sales: £" + String.format("%-6.2f", total));
} catch (FileNotFoundException e) {
System.out.println("Error - File does not exist");
}
}
}
A sample run:
This program will try to read data from a text file
Enter the file name: data2.txt
Transactions
================
Sold 34 Apple at £24.50
Line#2 is empty
Sold 53 Mango at £22.00
Line#4 is empty
Error in line#5: insufficient/invalid data
Line#6 is empty
Error in line#7: insufficient/invalid data
Total sales: £1999.00
Content of data2.txt:
111111,34,24.5,Apple
222222,53,22.0,Mango
333333,,32.0,Orange
44444,22,12.6,

Related

Java- Read from a .csv file and compute avg

How do I read a .csv Excel file with x number of rows and y number of columns, ignore irrelevant cells (things like names, or empty cells), then compute an average of the numbers in relevant cells?
I have managed to read a simple txt file, which looks like this:
Works fine with this, I get all the relevant info I need, but when I try to get data from a .csv file, it returns back the IOException
This is the .csv file:
public class Main {
/**
* Station name, read from input file
*/
private static String stationid = null;
/**
* Set of records, read from input file
*/
private static ArrayList<StationRecord> records = new ArrayList<>();
/**
* #param year
*/
public static void listMaxWindByYear(int year) {
records.sort((o1, o2) -> (o2.getMaxWind() - o1.getMaxWind()));
System.out.println("Max Wind by the Station during " + year);
System.out.printf("%-40s%-15s%-20s\n", "Station Name", "Max Wind", "Date");
System.out.printf("%-40s%-15s%-20s\n", "------------", "--------", "----");
int maxWind = records.get(0).getMaxWind();
for (StationRecord record : records) {
if (record.getMaxWind() == maxWind) {
System.out.printf("%-40s%-15d%-20s\n", stationid, record.getMaxWind(),
record.getMonth() + " " + record.getDay() + ", " + record.getYear());
} else {
break;
}
}
System.out.println();
}
public static void listMinWindByYear(int year) {
records.sort((o1, o2) -> (o1.getMinWind() - o2.getMinWind()));
System.out.println("Min Wind by the Station during " + year);
System.out.printf("%-40s%-15s%-20s\n", "Station Name", "Min Wind", "Date");
System.out.printf("%-40s%-15s%-20s\n", "------------", "--------", "----");
int minWind = records.get(0).getMinWind();
for (StationRecord record : records) {
if (record.getMinWind() == minWind) {
System.out.printf("%-40s%-15d%-20s\n", stationid, record.getMinWind(),
record.getMonth() + " " + record.getDay() + ", " + record.getYear());
} else {
break;
}
}
System.out.println();
}
public static double calculateAverageOfAverageWindByYear(int year) {
double total = 0;
int numRecords = 0;
for (StationRecord record : records) {
if (record.getYear() == year) {
total += record.getAverageWind();
numRecords++;
}
}
if (numRecords == 0) {
return 0;
}
return total / numRecords;
}
/**
*
* #param args Unused arguments
*/
public static void main(String[] args) {
Locale.setDefault(Locale.US);
File inputFile = null;
Scanner menuScanner = new Scanner(System.in);
while (true) {
try {
System.out.println("Please, enter input file name:");
inputFile = new File(menuScanner.nextLine());
parseFile(inputFile);
menuScanner.close();
break;
} catch (IOException ioe) {
System.out.println("File Name you entered is not relevant");
}
}
System.out.println();
listMaxWindByYear(2019);
listMinWindByYear(2019);
double overallAverageTemp = calculateAverageOfAverageWindByYear(2019);
System.out.println(stationid + " average Wind: " + String.format("%.1f", overallAverageTemp));
System.out.println();
}
private static void parseFile(File file) throws IOException {
Scanner scanner = null;
try {
scanner = new Scanner(file);
stationid = scanner.nextLine();
while (scanner.hasNextLine()) {
records.add(new StationRecord(scanner.nextLine()));
}
scanner.close();
} catch (InputMismatchException e) {
scanner.close();
throw new IOException();
} catch (NoSuchElementException e) {
scanner.close();
throw new IOException();
}
}
So summary of what it is intended to do, read the columns with windspeed list max and min values and calculate an average print on screen or file (only can do screen print at the mom).
Next step would be
Calculating monthly average, min, max of each year And Print to File .
I hope this is understandable and something I can get help with, I am really new to java and every help would be much appreciated.
Feel free to edit my code or lecture if necessary.

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);

How to add the bonus?

I have done a code, which reads a file consists a number of employees, salary, and their rankings, based on their rankings how can we add the bonus percent to their salary...
String phrases;
int salary=0;
try {
FileReader in = new FileReader("bonus.txt");
BufferedReader readFile = new BufferedReader(in);
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
double bonus;
if(phrases.contains("1")){
bonus=salary/0.03;
System.out.println("Bonus: " + bonus);
}else if(phrases.contains("2")){
bonus=salary/0.08;
System.out.println("Bonus: " + bonus);
}else if(phrases.contains("3")){
bonus=salary/0.20;
System.out.println("Bonus: " + bonus);
}
// System.out.println();
}
readFile.close();
in.close();
}catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
It outputs:
Jame 900000 1
Bonus: 0.0
Jane 60000 2
Bonus: 0.0
Don 866000 3
Bonus: 0.0
I have no idea why
If you have an employeeBonus.txt file like below.
Jame 900000 2
Jane 60000 1
Don 866000 3
I think you will have three tokens as a string so, you can use a stringtokenizer class in order to get a salary and a grade.
At the first line of file is
Jame 900000 2
and the result of encoded string was
Jame%20%20%20%20900000%092
I've finally found the content of text file was mixed with a space and tab character by URL encoding.
So, the usage of this type is as follows,
StringTokenizer stTok = new StringTokenizer(phrase, " \t");
It takes a salary and an identifier of bonus value from third and second token.
name = stTok.nextToken(); //first token
salary = Integer.valueOf(stTok.nextToken()).intValue(); //second token
grade = stTok.nextToken();
[source code]
package com.tobee.tests.inout;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class CheckBounsFromFile {
public static void main(String[] args) {
String name, phrase, grade;
double bonus = 0;
int salary = 0;
BufferedReader readFile = null;
try {
readFile = new BufferedReader(new FileReader("resource/aa/employeeBonus.txt"));
while ((phrase = readFile.readLine()) != null) {
//System.out.println(phrase);
StringTokenizer stTok = new StringTokenizer(phrase, " \t");
name = stTok.nextToken();
salary = Integer.valueOf(stTok.nextToken()).intValue();
grade = stTok.nextToken();
if(grade!= null && !grade.equals(""))
{
if (grade.equals("1")) {
bonus = salary / 0.03;
} else if (grade.equals("2")) {
bonus = salary / 0.08;
} else if (grade.equals("3")) {
bonus = salary / 0.20;
}
System.out.printf("name[%s]salary[%d]Bonus[%f] \n",name, salary, bonus);
}
}
} catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
finally
{
try {
readFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
[result]
name[Jame]salary[900000]Bonus[30000000.000000]
name[Jane]salary[60000]Bonus[750000.000000]
name[Don]salary[866000]Bonus[4330000.000000]
Have a nice day.
The other answers appear to not cater for the fact that your salary variable is always 0, thus, your bonus calculation, which depends on your salary value will always be 0.
Assuming that this: Jame 900000 1 is a sample line from your text file, there are various issues with your code.
The first issue is this: (phrases.equals("1"). If phrase will be equal to the text in the current line you are processing: Jame 900000 1, this statement (and the same for the other two) will never return true, thus the bonus will never be calculated.
The second issue is that you are never extracting the salary value.
You will need to replace this:
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
if(phrases.equals("1")){
With something like this:
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
String[] employeeData = phrases.split("\\t"); //This assumes that your data is split by tabs.
salary = Double.parse(employeeData[1]);
if("1".equals(employeeData[2])) {
bonus = salary * 0.03;
}
...
You check the condition with equals method but your phrases variable contains different value rather than 1,2,3 that's why you get the bonus 0.
if(phrases.contains("1")){
bonus=salary/0.03;
}else if(phrases.contains("2")){
bonus=salary/0.08;
}else if(phrases.contains("3")){
bonus=salary/0.20;
}
or you can get the last parameter with:
phrases.substring(phrases.length()-1, phrases.length())
you can get the third parameter using contains or split method.
Please check this tutorial: https://www.tutorialspoint.com/java/java_string_split.htm
And one more thing your salary is always zero (0). please correct it
I have posted full code here:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class SubClass{
public static void main(String[] args) {
String phrases;
int salary=0;
try {
FileReader in = new FileReader("bonus.txt");
BufferedReader readFile = new BufferedReader(in);
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
phrases = phrases.trim().replaceAll("[ ]{2,}", " ");
String splitStr [] = phrases.split(" ");
double bonus;
salary = Integer.parseInt(splitStr[1]);
if(splitStr[2].contains("1")){
bonus=salary/0.03;
System.out.println("Bonus: " + bonus);
}else if(splitStr[2].contains("2")){
bonus=salary/0.08;
System.out.println("Bonus: " + bonus);
}else if(splitStr[2].contains("3")){
bonus=salary/0.20;
System.out.println("Bonus: " + bonus);
}
// System.out.println();
}
readFile.close();
in.close();
}catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
}
}

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);
}
}
}

Displaying Information Within Random Access File

I have created an application that allows the user to enter their account number, balance(no more than 99999), and last name. The program will take this information and insert it into a .txt file at a location corresponding to the account number(acct). Here is the code for that:
import java.io.*;
public class NationalBank {
public static void main(String[] args) throws Exception{
InputStreamReader temp = null;
BufferedReader input = null;
try {
temp = new InputStreamReader(System.in);
input = new BufferedReader(temp);
int acct;
double amount;
String name;
RandomAccessFile file = new RandomAccessFile("bank.txt", "rw");
while(true) {
// Asks for input
System.out.println("Enter Account Number (0-9999): ");
acct = Integer.parseInt(input.readLine());
System.out.println("Enter Last Name: ");
name = input.readLine();
System.out.println("Enter Balance ");
amount = Double.parseDouble(input.readLine());
// Making sure account numbers are between 0 and 9999
if(acct >=0 && acct <= 9999) {
file.seek(acct*17);
file.write(truncateName(name));
file.writeBytes(" " +amount);
}
else {
continue;
}
// Asks user if more entries are needed
System.out.println("Enter More? (y/n)");
if (input.readLine().toLowerCase().equals("n"))
break;
}
file.close();
}
catch (Exception e) {
}
}
// Truncate/adding spaces to name until 8 characters
public static byte[] truncateName (String name) {
byte[] result = new byte[8];
for (int i = 0; i < 8; i++)
result [i] = i < name.length () ? (byte)name.charAt (i) : (byte)' ';
return result;
}
}
Now, I am trying to make an application that will write back all of the accounts that have information within them(with last name and balance). I need to display the account number, balance, and last name of those accounts. So far, I have:
import java.io.*;
public class DisplayBank {
public static void main(String[] args) throws IOException {
FileInputStream input = new FileInputStream ("bank.txt");
try {
byte[] record = new byte[17];
while (input.read(record) == 17) {
String name = new String(record, 0, 8);
long bits = 0;
for (int i = 8; i < 17; i++) {
bits <<= 8;
bits |= record[i] & 0xFF;
}
double amount = Double.longBitsToDouble(bits);
System.out.println("Account Number: " + record + " Name: " + name + ", amount: " + amount);
}
}
catch (IOException e) {
}
finally {
input.close();
}
}
}
This currently displays only the name correctly. The balance is incorrect, and I don't know how to get the account number. In order to get the account number, I would need to get the position of name. In order to get the amount, I would need to seek name, offset 9 bytes, then read the next 8 bytes...
If you want to parse a text file that contains last names and amounts similar what you provided:
example provided
LastName 93942.12
What I would do is to try something like the following
public void read_file(){
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:\\Users\\Alos\\Desktop\\test.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int record = 0;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String[] splits = strLine.split("\t");
String LastName = splits[0];
String Amount = splits[1];
System.out.println("Account Number: " + record + " Name: " + LastName + ", amount: " + Amount);
record++;
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
This might not be exactly what you're looking for but please take a look and update your question if you would like something different.
I it's not a homework, I would strongly recommend to use some RDBMS like Derby or MySQL.

Categories

Resources