How to read from a text-file. - java

I would like to know how can I check for a specific string on a line of a text file, save it in an array, and then move on to the next line of that text file.
For e.g.:
(what he is/ year edition/name/age/profession/number)
competitor 2014 joseph 21 student 20232341
competitor 2013 michael 23 engineer 23425123
As output, it would give me this:
Song Festival'2014
here are the competitors:
Joseph, student of 21 years - 20232341
Song Festival'2013
are the competitors
Michael, engineer of 23 years - 23425123
edit: java language

For this you would use a BufferedReader, you can format things in the text file using the tab (indent) which would be read from the BufferedReader as '\t' I'll write an example for you in a moment.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class StackoverflowExample {
private static final int INFORMATION_CAP = 100;
private static String[][] INFORMATION = new String[INFORMATION_CAP][INFORMATION_CAP];
public StackoverflowExample() {
String currentLine;
String[] textData;
int lineID = 0;
boolean endOfFile = false;
try {
BufferedReader reader = new BufferedReader(new FileReader("textfile.txt"));
currentLine = reader.readLine();
while(!endOfFile && currentLine != null) {
currentLine = currentLine.trim();
textData = currentLine.split("\\t");
String userType = textData[0];
String year = textData[1];
String name = textData[2];
String age = textData[3];
String profession = textData[4];
String number = textData[5];
INFORMATION[lineID] = new String[] { userType, year, name, age, profession, number };
lineID++;
currentLine = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new StackoverflowExample();
for(int i = 0; i < INFORMATION.length; i++) {
System.out.println("Type: " + INFORMATION[i][0] +
"year: " + INFORMATION[i][1] +
"name: " + INFORMATION[i][2] +
"age: " + INFORMATION[i][3] +
"profession: " + INFORMATION[i][4] +
"number: " + INFORMATION[i][5]);
}
}
}
Create a text file called "textfile.txt" in your projects main directory, and format it like this
type(tab)year(tab)name(tab)age(tab)profession(tab)number(newline)

Related

Is there a way to collect data in multiple excel files?

there are 12 excel files that contain different products sales data, I try to sum up each month and entire year's sales using java but I can't add up sales for the whole year. Is there a way to do that? Thanks for your help.
public class Main {
public static void listOfSales(String fileName,String month){
List<PriceList> list = readsListFroExcel(fileName);
int sumOfInYearSale = 0;
int sumOfInOnlineSale =0;
int sumOfTotalMonthlySale = 0;
for (PriceList x : list){
sumOfInYearSale = sumOfInYearSale + x.getTotalPhysicalSale();
sumOfInOnlineSale = sumOfInYearSale + x.getTotalOnlineSale();
}
System.out.println(month +" Physical Sales : "+sumOfInYearSale);
System.out.println(month+ " Online Sales :" +sumOfInOnlineSale);
}
private static List<PriceList> readsListFroExcel(String fileName) {
List<PriceList> list = new ArrayList<>();
Path pathTofile = Paths.get(fileName);
try (BufferedReader br = Files.newBufferedReader(pathTofile)){
String headerLine = br.readLine();
String line = br.readLine();
while (line!=null){
String[] attributes = line.split(",");
PriceList listOfPrice = createList(attributes);
list.add(listOfPrice);
line = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
}

How to add Timestamp in JAVA code like count (in each line) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a java code which takes data from CSV file and shows as html in tabular form.
I want to add timestamp should appear automatically like count appears at start of each row.
It have three JAVA files which I have pasted below all together.
Please advice what code shall I add and where exactly to fulfill timestamp requirement.
Below is the code example:
package display;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class Play
{
public static List <LineInfo> INFO = new ArrayList<LineInfo>();
///////////////////////////////////////////////////////////////////////////////////////////
public static void loadInfo() throws IOException
{
int count = 0;
String filePath = "C:\\folder\\";
String fileName = "file.csv";
BufferedReader csvReader = new BufferedReader(new FileReader(filePath + fileName));
String row = "";
/////////////////////////////////////////////////////////////////////////////////
while ((row = csvReader.readLine()) != null)
{
count++;
String[] raw = row.split(",");
//System.out.println(row);
String[] data = new String[20];
for (int i = 0; i < raw.length; i++)
{
data[i] = raw[i];
}
for (int i = 0; i < data.length; i++)
{
if(data[i] == null)
data[i] = "";
}
LineInfo line = new LineInfo(count, data[0], data[1], data[2], data[3], data[4]);
INFO.add(line);
}
//////////////////////////////////////////////////////////////////////////////
csvReader.close();
System.out.println("File loaded successfully total records : " + (INFO.size() -1));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void htmlIT() throws IOException
{
HTMLify html = new HTMLify(INFO);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) throws IOException, InterruptedException
{
int i = 0;
while (i < 1)
{
loadInfo();
htmlIT();
INFO.clear();
//wait
TimeUnit.SECONDS.sleep(300);
}
}
}
----------------------------------------------------
package display;
/////////////////////////////////////////////////////////////////////////////////////////////////////
import java.io.IOException;
public class LineInfo {
int seq = 0; // system sequence number
String ser = ""; //
String subject = ""; //
String title1 = ""; //
String title2 = ""; //
String title3 = ""; //
//////////////////////////////////////////////////////////////////////////////////////////////////////
public LineInfo(int sn, String sr, String sbj, String t1, String t2, String t3) throws IOException
{
this.seq = sn;
this.ser = sr;
this.subject = sbj;
this.title1 = t1;
this.title2 = t2;
this.title3 = t3;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
}
-------------------------------------------------------
package display;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class HTMLify
{
public static List <LineInfo> INFO = new ArrayList<LineInfo>();
public static List <String> SUBJECT = new ArrayList<String>();
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void ddHTML() throws IOException
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
StringBuilder htmlDD = new StringBuilder();
htmlDD.append("<html><head><meta http-equiv=\"refresh\" content=\"30\"/><title> SHEET </title>");
htmlDD.append("<body bgcolor=\"#ffffff\">");
//Report style
htmlDD.append("<style type=\"text/css\">");
htmlDD.append(".tg {border-collapse:collapse;border-spacing:0;}");
htmlDD.append(".tg td{font-family:Arial, sans-serif;font-size:22px;padding:10px 5px;border-style:0;border-width:0px;overflow:hidden;word-break:normal;}");
htmlDD.append(".tg th{font-family:Arial, sans-serif;font-size:22px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}");
htmlDD.append(".tg .tg-smpa{font-weight:bold;font-size:40px;bold;background-color:#e8e8e8;color:#000000;text-align:center}");
htmlDD.append(".tg .tg-w672{font-weight:bold;font-size:22px;background-color:#5B5B5B;color:#ffffff;text-align:center;text-align:center;vertical-align:top}");
htmlDD.append(".tg .tg-jmap{font-weight:bold;font-size:22px;text-shadow: rgba(245,245,245,0.5) 1px 2px 1px;background-color:#000000;text-align:center;color:#ffffff;text-align:center;vertical-align:center}");
htmlDD.append(".tg .tg-cgn1{background-color:#FFFFFF;text-align:center;color:#585858;vertical-align:center}");
htmlDD.append("</style>");
htmlDD.append("</head>");
htmlDD.append("<table align=\"center\" class=\"tg\">");
htmlDD.append("<center><tr><td class=\"tg-smpa\" colspan=\"13\"><img src=\"\\4FW\\images\\header.png\" style=\"float:center;\"></td></tr></center>");
for (int i = 0; i < SUBJECT.size(); i++)
{
int count = 0;
htmlDD.append("<center><tr><th class=\"tg-smpa\" colspan=\"7\">" + SUBJECT.get(i) + "</th></tr></center>");
htmlDD.append("<tr><td class=\"tg-jmap\">" + INFO.get(0).ser + "</td><td class=\"tg-jmap\">" + INFO.get(0).title1 + "</td><td class=\"tg-jmap\">" + INFO.get(0).title2 + "</td><td class=\"tg-jmap\">" + INFO.get(0).title3 + " </td></tr>");
for (int z = 1; z < INFO.size(); z++)
{
if(SUBJECT.get(i).equals(INFO.get(z).subject))
{
count++;
htmlDD.append("<tr><td class=\"tg-cgn1\">" + count +
"</td><td class=\"tg-cgn1\">" +"<img src=\"\\folder\\images\\Alerts\\" + INFO.get(z).title1 + ".gif\" style=\"float:center;\">" +
"</td><td class=\"tg-cgn1\">" + INFO.get(z).title2 +
"</td><td class=\"tg-cgn1\">" + INFO.get(z).title3 +
"</td></tr>");
}
}
htmlDD.append("<tr><td></td></tr>");
}
//htmlDD.append("<tr><td></td></tr>");
htmlDD.append("<center><tr><td class=\"tg-smpa\" colspan=\"7\"><img src=\"\\4FW\\images\\footer.png\" style=\"float:center;\"></td></tr></center>");
htmlDD.append("</table></body></html>");
File saveLocal = new File("C:\\xampp\\htdocs\\newfolder\\index.html");
BufferedWriter writer = new BufferedWriter(new FileWriter(saveLocal));
writer.write(htmlDD.toString());
writer.close();
System.out.println("Display file generated.");
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public HTMLify (List <LineInfo> info) throws IOException
{
this.INFO = info;
List <String> subj = new ArrayList<String>();
for (int i =1; i < info.size(); i++)
{
String sbj = info.get(i).subject;
subj.add(sbj);
}
SUBJECT = subj.stream().distinct().collect(Collectors.toList());
ddHTML();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
Thanks in advance.
You can do it as follows:
htmlDD.append("<tr><td>" + System.currentTimeMillis() + "</td><td class=\"tg-cgn1\">" + count +
"</td>....
Make sure to add the heading column for the timestamp (i.e. <th>Timestamp</th>) otherwise, the table will appear distorted.
Update
(to answer further questions from the comment)
It appeared as milli sec as 14 digit continues number. How can I
convert it in format like yyyy-mm-dd hh:mm.
You can convert to whatever format you like using DateTimeFormatter but I think all you want is to display all parts (year, month, day, hour, minute, second, nanosecond) of the date-time and therefore, you can simply replace System.currentTimeMillis() with Instant.now().
I want new timestamp for new row only and previously added row should
have fixed timestamp at the time when that row added in CSV file. But
as of now when I save CSV file after adding new row and run program.
It changes time for all rows to current time. Is it possible?
It is not a big deal. In order to do it, instead of generating the timestamp as part of this program, you can store the value of Instant.now() in some file or database and then fetch the same in this program.

optimising the search time in hashmap

I have a csv file which is hashmapped, whenever the user enter the city name(key) it will display all the details of that city. I have to optimize the search result time, everytime the it is reading the file(instead of only once) and displaying the values.
The CSV files contains data like this :
city,city_ascii,lat,lng,country,iso2,iso3,admin_name,capital,population,id
Malishevë,Malisheve,42.4822,20.7458,Kosovo,XK,XKS,Malishevë,admin,,1901597212
Prizren,Prizren,42.2139,20.7397,Kosovo,XK,XKS,Prizren,admin,,1901360309
Zubin Potok,Zubin Potok,42.9144,20.6897,Kosovo,XK,XKS,Zubin
Potok,admin,,1901608808
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.io.IOException;
public class CSVFileReaders{
public static void main(String[] args) {
String filePath = "C:\\worldcities1.csv";
Scanner in = new Scanner(System.in);
System.out.println(" \n Enter the City name to be Searched : \n _> ");
long start = System.currentTimeMillis();
String searchTerm = in.nextLine();
readAndFindRecordFromCSV(filePath, searchTerm);
long end = System.currentTimeMillis();
System.out.println(" \n It took " + (end - start) + " Milli Seconds to search the result \n");
in.close();
}
public static void readAndFindRecordFromCSV( String filePath, String searchTerm) {
try{
HashMap<String,ArrayList<String>> cityMap = new HashMap<String,ArrayList<String>>();
Scanner x = new Scanner (new File(filePath),"UTF-8");
String city= "";
while(x.hasNextLine()) {
ArrayList<String> values = new ArrayList<String>();
String name = x.nextLine();
//break each line of the csv file to its elements
String[] line = name.split(",");
city = line[1];
for(int i=0;i<line.length;i++){
values.add(line[i]);
}
cityMap.put(city,values);
}
x.close();
//Search the city
if(cityMap.containsKey(searchTerm)) {
System.out.println("City name is : "+searchTerm+"\nCity details are accordingly in the order :"
+ "\n[city , city_ascii , lat , lng , country , iso2 , iso3 , admin_name , capital , population , id] \n"
+cityMap.get(searchTerm)+"");
}
else {
System.out.println("Enter the correct City name");
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}`
the time should be optimized and every time i search it is reading the entire file(which should happen)
Currently you mix the map initialization inside the search function.
You don't want that.
First, init the map, then use it in the search function.
To do that, extract a method for statements that instantiate and value the map and then refactor the readAndFindRecordFromCSV() method so that it accepts a Map as additional parameter :
public static void readAndFindRecordFromCSV( String filePath, String searchTerm, HashMap<String,ArrayList<String>> dataByCity) {...}
With refactoring IDE features, it should be simple enough : "extracting method" then "change signature".
Here is a code (not tested at runtime but tested at compile time) that splits the logical in separated tasks and also rely on instance methods :
public class CSVFileReaders {
private final String csvFile;
private HashMap<String, ArrayList<String>> cityMap;
private final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
String filePath = "C:\\worldcities1.csv";
CSVFileReaders csvFileReaders = new CSVFileReaders(filePath);
csvFileReaders.createCitiesMap();
csvFileReaders.processUserFindRequest(); // First search
csvFileReaders.processUserFindRequest(); // Second search
}
public CSVFileReaders(String csvFile) {
this.csvFile = csvFile;
}
public void createCitiesMap() {
cityMap = new HashMap<>();
try (Scanner x = new Scanner(new File(csvFile), "UTF-8")) {
String city = "";
while (x.hasNextLine()) {
ArrayList<String> values = new ArrayList<String>();
String name = x.nextLine();
//break each line of the csv file to its elements
String[] line = name.split(",");
city = line[1];
for (int i = 0; i < line.length; i++) {
values.add(line[i]);
}
cityMap.put(city, values);
}
x.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
public void processUserFindRequest() {
System.out.println(" \n Enter the City name to be Searched : \n _> ");
long start = System.currentTimeMillis();
String searchTerm = in.nextLine();
long end = System.currentTimeMillis();
System.out.println(" \n It took " + (end - start) + " Milli Seconds to search the result \n");
//Search the city
if (cityMap.containsKey(searchTerm)) {
System.out.println("City name is : " + searchTerm + "\nCity details are accordingly in the order :"
+ "\n[city , city_ascii , lat , lng , country , iso2 , iso3 , admin_name , capital , population , id] \n"
+ cityMap.get(searchTerm) + "");
} else {
System.out.println("Enter the correct City name");
}
}
}
The interesting part is here :
String filePath = "C:\\worldcities1.csv";
CSVFileReaders csvFileReaders = new CSVFileReaders(filePath);
csvFileReaders.createCitiesMap();
csvFileReaders.processUserFindRequest(); // First search
csvFileReaders.processUserFindRequest(); // Second search
The logical is clearer now.
Why do you create / load the CSV into a HashMap with every search ?
Just create the HashMap only once in the beginning, and then on every search just check whether it exists in the HashMap, eg move the read part into a separate method :
HashMap<String,ArrayList<String>> cityMap = new HashMap<String,ArrayList<String>>();
public static void readCSVIntoHashMap( String filePath) {
try{
Scanner x = new Scanner (new File(filePath),"UTF-8");
String city= "";
while(x.hasNextLine()) {
ArrayList<String> values = new ArrayList<String>();
String name = x.nextLine();
//break each line of the csv file to its elements
String[] line = name.split(",");
city = line[1];
for(int i=0;i<line.length;i++){
values.add(line[i]);
}
cityMap.put(city,values);
}
x.close();
...
}
Then have a separate method for searching :
public static void search(String searchTerm) {
if(cityMap.containsKey(searchTerm)) {
...
}
}

Read txt file into array and assign to variables

So essentially what I need to do is make this while loop run through the txt file and store it in an array to be stored inside the instance variables
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* <insert class description here>
*
* #author Chris Crosby
*
*/
public class TrackInput
{
private Scanner keyboard = new Scanner(System.in);
public int readTrackData(Railroad[] Reservations) {
final String FILE_NAME = "TrackData.txt";
int size =0;
Scanner input = null;
try {
input= new Scanner(new File(FILE_NAME));
}
catch(FileNotFoundException e) {
System.out.println("Unable to open file " + FILE_NAME + ".");
}
String passengerName="";
String routeNumber="";
String departureDate="";
String departureTrack="";
String arrivalTrack="";
String departureTime="";
String arrivalTime="";
String seat="";
String returnRouteNumber="";
String ReturnDate="";
while (input.hasNext()&& size<Reservations.length) {
}
return size;
}
}
here's the txt file that the loop is reading through
Carl Foreman
1234
UA1235
06/23/2014
ORD
LGA
4:00 PM
7:15 PM
23A
UA673
07/12/2014
LGA
ORD
10:00 AM
11:25 AM
8A
Jennifer Foreman
1235
UA1235
06/23/2014
ORD
LGA
4:00 PM
7:15 PM
23B
UA673
07/12/2014
LGA
ORD
10:00 AM
11:25 AM
8B
Jane Anderson
4577
UA317
08/04/2014
ORD
SFO
8:10 AM
10:45 AM
11C
UA728
08/14/2014
SFO
ORD
12:52 PM
7:03 PM
10D
Jason Anderson
4578
TrackData.txt format
passenger name – include first and last name in one variable
reservation number
departure route number
departure date
departure track
arrival track
departure time
arrival time
seat
return route number
return date
departure track
arrival track
departure time
arrival time
seat
here's a similar method I had to write for a previous assignment
public int readInventory(Automobile[] inventory)
{
final String FILENAME = "inventory.csv";
int size = 0;
Scanner input = null;
try
{
input = new Scanner(new File(FILENAME));
}
catch (FileNotFoundException e)
{
System.out.println("Unable to open file " + FILENAME + ".");
}
// read header line and discard first line
String line = input.nextLine();
// create vars
int year = 0;
String make = "";
String model = "";
double price = 0.0;
String condition = "";
int rating = 0;
String status = "";
String vin = "";
// Customer vars
String firstName = "";
String lastName = "";
String streetAddress = "";
String city = "";
String state = "";
String zip = "";
String email = "";
String phone = "";
while (input.hasNext() && size < inventory.length)
{
line = input.nextLine();
String[] record = line.split(",");
year = Integer.parseInt(record[0]);
make = record[1];
model = record[2];
// If use this version, comment out the following if statements
if (!(record[3].equals("")))
{
price = Double.parseDouble(record[3]);
}
else
{
price = 0;
}
condition = record[4];
if (!(record[5].equals("")))
{
rating = Integer.parseInt(record[5]);
}
else
{
rating = 0;
}
status = record[6];
vin = record[7];
// this is where the records differ
// they either don't have buyer information or some do
if (record.length > 8)
{
if (!(record[8].equals("")))
firstName = record[8];
else
firstName = "";
if (!(record[9].equals("")))
lastName = record[9];
else
lastName = "";
if (!(record[10].equals("")))
streetAddress = record[10];
else
streetAddress = "";
if (!(record[11].equals("")))
city = record[11];
else
city = "";
if (!(record[12].equals("")))
state = record[12];
else
state = "";
if (!(record[13].equals("")))
zip = record[13];
else
zip = "";
if (!(record[14].equals("")))
email = record[14];
else
email = "";
if (!(record[15].equals("")))
phone = record[15];
else
phone = "";
}
// changes to integrate Customer class go below
Customer tempCustomer = new Customer(firstName,lastName, city, state, email, phone,zip,streetAddress);
Automobile tempAutomobile = new Automobile( year, make, model, price,
condition, rating, status, vin, tempCustomer);
inventory[size] = tempAutomobile;
size++;
} // end of while loop
input.close();
return size;
}
not sure how to make it work for this program since this is multilined and the previous was a single line separated by commas hence the line.split
Hmmm... I am not sure i should answer this since it is not that hard and i am sure you can solve it yourself. Sadly i dont have enough reputation to just comment (that is why i am here in the first place).
I will just drop some hints to help you:
1) You know how to read line by line. You can choose when to start, stop and even skip lines. Sadly you can only move forward but that is enough for this problem.
2) The data file follows a constant pattern. This means this is the easy to handle data.
3) You know the pattern beforehand. Pst, it is the OP!
I think that is it. Now you should just pay attention and wait for the AHA! moment.
package edu.ilstu;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* <insert class description here>
*
* #author Chris Crosby
*
*/
public class TrackInput
{
public final String TRANSACTION_FILE = "Transactions.txt";
public final String DATA_FILE = "RailroadData.txt";
public TrackInput() {
}
Scanner transaction = null;
public Scanner readTransactions() {
try {
transaction= new Scanner(new File(TRANSACTION_FILE));
}
catch(FileNotFoundException e){
System.out.println("Unable to open file" + TRANSACTION_FILE);
System.exit(1);
}
return transaction;
}
public char readTransactionCode() {
char choice = transaction.nextLine().charAt(0);
return choice;
}
public int readRailroadData(Reservation [] reservations) {
Scanner data;
int count = 0;
try {
data = new Scanner(new File(DATA_FILE));
while(data.hasNext()) {
Reservation reservation = readReservationData(data);
reservations [count] = reservation;
count++;
}
}
catch(FileNotFoundException e){
System.out.println("Unable to open file" + DATA_FILE);
System.exit(1);
}
return count;
}
public Reservation readReservationData(Scanner input) {
String name = input.nextLine();
String departureReservationNumber=input.nextLine();
String departureRouteNumber = input.nextLine();
String departureRouteDate = input.nextLine();
String departureTrack = input.nextLine();
String departureArrivalTrack = input.nextLine();
String departureTime = input.nextLine();
String departureArrivalTime = input.nextLine();
String departureSeatAssignment = input.nextLine();
String returnRoute = input.nextLine();
String returnDate = input.nextLine();
String returnDepartureTrack = input.nextLine();
String returnArrivalTrack = input.nextLine();
String returnDepartureTime = input.nextLine();
String returnArrivalTime = input.nextLine();
String returnSeatAssignment = input.nextLine();
Route departureRoute = new Route(departureRouteNumber, departureRouteDate, departureTrack, departureArrivalTrack,departureTime, departureArrivalTime, departureSeatAssignment);
Route arrivalRoute= new Route(returnRoute, returnDate, returnDepartureTrack, returnArrivalTrack,returnDepartureTime,returnArrivalTime,returnSeatAssignment);
Reservation reservation = new Reservation(name,departureReservationNumber, departureRoute, arrivalRoute);
return reservation;
}
public int addReservationToList(Reservation[] reservationList,Reservation reservation, int size) {
reservationList[size] = reservation;
size++;
return size;
}
}

java read text file column headers in random order

I recieve a file each day that:
is stab delimited
has 5 or more columns
has 3 common columns - lastName, firstName, address
Problem: the column order of the file changes regularly
Goal: print column data for lastName, firstName, address regardless of column order
I have been using the following code and manually changing the datavalues to match the columns.
testfile1.txt
1st day file format
ID lastName address phone firstName
45 Gates 111 some lane 777-888-9999 Bill
2nd day file format
address ID phone firstName lastName
111 some lane 81 444-555-1111 John Doe
-
import java.io.BufferedReader;
import java.io.FileReader;
public class test2 {
public static void main(String args[]) throws Exception {
String dataFileName = "C:/testfiles/testfile1.txt";
String line;
int lineNumber = 0;
BufferedReader bReader = new BufferedReader(new FileReader(dataFileName));
bReader.readLine();
while ((line = bReader.readLine()) != null) {
lineNumber++;
String datavalue[] = line.split("\t");
String lastName = datavalue[1];
String firstName = datavalue[5];
String address = datavalue[3];
System.out.println(lastName + "'" + firstName + "," + address);
}
}
}
This is a first approach. I would try it somehow like this:
int colLastName, colFirstName, colAddress;
line = bReader.readLine();
String columnOrder []= line.split("\t");
for (int i=0; i< columnOrder.length; i++){
if (columnOrder[i].equals("lastName")){
colLastName = i;
}
else if (columnOrder[i].equals("firstName"){
colFirstName = i;
}
else if (columnOrder[i].equals("address"){
colAddress = i;
}
}
while ((line = bReader.readLine()) != null) {
lineNumber++;
String datavalue[] = line.split("\t");
String lastName = datavalue[colLastName];
String firstName = datavalue[colFirstName];
String address = datavalue[colAddress];
System.out.println(lastName + "'" + firstName + "," + address);
}
I think you can try something like below -
import java.io.BufferedReader;
import java.io.FileReader;
public class test2 {
public static void main(String args[]) throws Exception {
String dataFileName = "C:/testfiles/testfile1.txt";
String line;
boolean isFirstColumn = true;
BufferedReader bReader = new BufferedReader(new FileReader(dataFileName));
int[] order_Fname_Lname_Address = new int[3];
while ((line = bReader.readLine()) != null) {
String datavalue[] = line.split("\t");
if(isFirstColumn) {
for (int i = 0; i < datavalue.length; i++) {
switch (datavalue[i]) {
case "firstName":
order_Fname_Lname_Address[0] = i;
break;
case "lastName":
order_Fname_Lname_Address[1] = i;
break;
case "address":
order_Fname_Lname_Address[2] = i;
break;
}
}
isFirstColumn = false;
continue;
}
String firstName = datavalue[order_Fname_Lname_Address[0]];
String lastName = datavalue[order_Fname_Lname_Address[1]];
String address = datavalue[order_Fname_Lname_Address[2]];
System.out.println(lastName + " " + firstName + "," + address);
}
bReader.close();
}
}

Categories

Resources