I know this question might be answered many times. However, I still cannot solve this specific problem.
Basically I have a .txt file with the following format.
String Integer String
For example,
la 789 ferrari
turbo 560 porsche
veyron 987 bugatti
sls 563 benz
dbs 510 aston
How can I read the file line by line and store the numbers/integers ONLY into arraylist?
Thank you!
Here's a more full Java-esque solution, using Java 7 ... for fun.
Main.java
import java.util.List;
public class Main
{
private static final InputFileParser inputFileParser = new InputFileParser();
private static final EntryNumberExtractor extractor = new EntryNumberExtractor();
private static final String FILENAME = "input-file.txt";
public static void main(String... args)
{
List<Entry> entries = inputFileParser.parse(FILENAME);
List<Integer> extractedIntegers = extractor.extract(entries);
System.out.println("Entries: ");
prettyPrintListItems(entries);
System.out.println();
System.out.println("Entry numbers: ");
prettyPrintListItems(extractedIntegers);
}
private static <T> void prettyPrintListItems(List<T> list)
{
for (T item : list)
{
System.out.println(item);
}
}
}
InputFileParser.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class InputFileParser
{
public List<Entry> parse(String filename)
{
List<Entry> entries = new ArrayList<>();
File f = new File(filename);
try (BufferedReader reader = new BufferedReader(new FileReader(f));)
{
String line = null;
while ((line = reader.readLine()) != null)
{
String[] components = line.split(" ");
entries.add(new Entry(components[0], Integer.parseInt(components[1]), components[2]));
}
}
catch (IOException e)
{
e.printStackTrace();
}
return entries;
}
}
EntryNumberExtractor.java
import java.util.ArrayList;
import java.util.List;
public class EntryNumberExtractor
{
public List<Integer> extract(List<Entry> entries)
{
List<Integer> integers = new ArrayList<>();
for (Entry e : entries)
{
integers.add(e.getNumber());
}
return integers;
}
}
Entry.java
public class Entry
{
private String model;
private int number;
private String company;
public Entry(String model, int number, String company)
{
this.model = model;
this.number = number;
this.company = company;
}
public Integer getNumber()
{
return number;
}
#Override
public String toString()
{
return "model: " + model + ", number: " + number + ", company: " + company;
}
}
ArrayList<int> list = new ArrayList<int>();
try {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line = br.readLine();
while(line != null)
{
String[] tokens = line.Split(" ");
list.Add(Integer.parseInt(tokens[1]));
line = br.readLine()
}
catch(Exception e)
{
//Probably a conversation exception or a index out of bounds exception
}
You can read each line and split the line string by space, retrieve the number and store it in array list
Related
Excel file I'm using
I want to parse a csv file and extract the name, like 'chair' and then a list of each possible colour, so ['Blue','Green','Yellow']. How can I do this?
I have created a class Object, that has a 'String name' and a 'Listcolours'.
CSVReader reader = new CSVReader(new FileReader(new File(url.toURI()).getAbsolutePath()));
Object<API> listings = new ArrayList<Object>();
String [] line;
List<String> colourList = new ArrayList<>();
reader.readNext();
while ((line = reader.readNext()) != null) {
String name = line[0];
String colour = line[1];
colourList.add(operation);
Object object = new Object(name,colourList);
listings.add(object);
}
You can create a Hashmap with key as name of the item and value as list of colors available.
I hope below snippet will solve your problem. Good Luck!!
HashMap<String,List<String>> data = new HashMap<>();
String [] line;
reader.readNext();
while ((line = reader.readNext()) != null) {
String name = line[0];
String colour = line[1];
if(data.containsKey(name.toLowerCase())){
data.get(name.toLowerCase()).add(colour.toLowerCase());
}
else{
List<String> colorList = new ArrayList<>();
colorList.add(colour.toLowerCase());
data.put(name.toLowerCase(),colorList);
}
}
#g00se what do you mean by a 'stream grouping operation'
I'll show you. Actually, in your case, since you're using a proper csv API, you can leverage that to create beans first, then do the grouping. Here's what I mean by stream grouping: we create a Map<String, HouseholdObject>> (yes that's my name for your entities - pity it's got the word 'object' in it, but never mind). That collects them into groups having the same name:
package com.technojeeves.opencsvbeans;
import com.opencsv.bean.CsvToBeanBuilder;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.*;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class HouseholdParser {
public static void main(String[] args) {
try {
List<HouseholdObject> objects = new HouseholdParser().read(new File(args[0]));
Map<String, List<HouseholdObject>> objectsGroupedByName =
objects.stream()
.skip(1)
.collect(groupingBy(HouseholdObject::getName));
System.out.println("The following groups of household objects were found:");
objectsGroupedByName.entrySet()
.stream()
.forEach(e -> {
System.out.println(e.getKey());
e.getValue()
.stream()
.forEach(v -> System.out.printf("\t%s%n", v.getColour()));
});
} catch (Throwable t) {
t.printStackTrace();
}
}
public List<HouseholdObject> read(File file) {
try (FileReader reader = new FileReader(file)) {
return new CsvToBeanBuilder(reader).withType(HouseholdObject.class).build().parse();
} catch (IOException e) {
throw new RuntimeException("Cannot read file: " + file.getName() + e);
}
}
}
Here's the bean I made for it:
package com.technojeeves.opencsvbeans;
import com.opencsv.bean.CsvBindByPosition;
import com.opencsv.bean.CsvCustomBindByPosition;
import com.opencsv.bean.AbstractBeanField;
import com.opencsv.bean.CsvRecurse;
public class HouseholdObject {
#CsvBindByPosition(position = 0)
private String name;
#CsvBindByPosition(position = 1)
private String colour;
public HouseholdObject() {
}
public HouseholdObject(String name, String colour) {
this.name = name;
this.colour = colour;
}
public String getName() {
return this.name;
}
public String getColour() {
return this.colour;
}
public void setName(String name) {
this.name = name;
}
public void setColour(String colour) {
this.colour = colour;
}
#Override
public String toString() {
return String.format("%s=%s,%s=%s", "name", name, "colour", colour);
}
#Override
public boolean equals(Object o) {
HouseholdObject other = (HouseholdObject)o;
return name.equals(other.name) && colour.equals(other.colour);
}
#Override
public int hashCode() {
return name.hashCode() * colour.hashCode();
}
}
And here's my output with your source CSV:
The following groups of household objects were found:
Table
Purple
Pink
Chair
Blue
Green
Yellow
Door
Yellow
I have two arraylists
arraylist dName has values:
mark, 22
peter, 34
ken, 55
arraylist dest has values:
mark, London
peter, Bristol
mark, Cambridge
I want to join merge them so that their output gives:
mark
London
Cambridge
peter
Bristol
Ken
this is the code i have for now, i'm not really usre how to split on the comma and search the other array
public class Sample {
BufferedReader br;
BufferedReader br2;
public Sample() {
ArrayList<String> dName = new ArrayList<String>();
ArrayList<String> dest = new ArrayList<String>();
String line = null;
String lines = null;
try {
br = new BufferedReader(new FileReader("taxi_details.txt"));
br2 = new BufferedReader(new FileReader("2017_journeys.txt"));
while ((line = br.readLine()) != null &&
(lines = br2.readLine()) != null){
String name [] = line.split(";");
String destination [] = lines.split(",");
// add values to ArrayList
dName.add(line);
dest.add(lines);
// iterate through destination
for (String str : destination) {
}
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
}
}
Now, I'm not sure whether this is the proper way, but at least it is working.
taxi_details.txt
mark, 22
peter, 34
ken, 55
2017_journeys.txt
mark, London
peter, Bristol
mark, Cambridge
FileReader
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.stream.Collectors;
public class FileReader {
public List<String> read(String fileName) throws IOException{
return Files.lines(new File(fileName).toPath()).collect(Collectors.toList());
}
}
This class lets you avoid all the messy try-catch blocks.
Line
public class Line{
public static final String DELIMITER = ",";
public static final int INDEX_NAME = 0;
public static final int INDEX_VALUE = 1;
private String line;
private String[] values;
public Line(String line) {
this.line = line;
this.values = line.split(DELIMITER);
}
public String getName(){
return this.values[INDEX_NAME];
}
public String getValue(){
return this.values[INDEX_VALUE];
}
public void emptyValue(){
this.values[INDEX_VALUE] = "";
}
#Override
public String toString() {
return this.line;
}
}
This class has the mere prupose of preparing the data as needed for merging.
Main
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader();
// Read lines
List<String> dName = fileReader.read("taxi_details.txt");
List<String> dest = fileReader.read("2017_journeys.txt");
// Convert into proper format
List<Line> dNameLines = dName.stream().map(Line::new).collect(Collectors.toList());
List<Line> destLines = dest.stream().map(Line::new).collect(Collectors.toList());
// Remove ID
dNameLines.forEach(Line::emptyValue);
// Merge lists
Map<String, String> joined = join(dNameLines, destLines);
// Print
for (Entry<String, String> line: joined.entrySet()) {
System.out.println(line.getKey() + " --> " + line.getValue());
}
}
public static Map<String, String> join(List<Line> a, List<Line> b){
Map<String, String> joined = new HashMap<>();
// Put first list into map, as there is no danger of overwriting existing values
a.forEach(line -> {
joined.put(line.getName(), line.getValue());
});
// Put second list into map, but check for existing keys
b.forEach(line -> {
String key = line.getName();
if(joined.containsKey(key)){ // Actual merge
String existingValue = joined.get(key);
String newValue = line.getValue();
if(!existingValue.isEmpty()){
newValue = existingValue + Line.DELIMITER + newValue;
}
joined.put(key, newValue);
}else{ // Add entry normally
joined.put(line.getName(), line.getValue());
}
});
return joined;
}
}
You might want to move the join method into its own class.
Output
peter --> Bristol
ken -->
mark --> London, Cambridge
You should iterate on array B.
For each string, split on the comma and search in A for a string that starts with the first part of the split.
Then append the second part of the split to the entry found in A.
Currently, I'm at the point where I have only sorted the names within the file but I want to also make it so that ages can be sort. Another problem would be trying to get names that are the same but have different ages to sort. Right now my code looks something like this:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MultiKey {
public static void main(String[] args) {
File textFile = new File("H:\\Names_ages.txt");
FileReader in;
BufferedReader readFile;
String lineOfText;
try {
in = new FileReader(textFile);
readFile = new BufferedReader(in);
BufferedReader reader = new BufferedReader(new FileReader(textFile));
List<String> results = new ArrayList<String>();
while ((lineOfText = readFile.readLine()) != null) {
results.add(lineOfText);
}
Collections.sort(results);
System.out.println(results);
readFile.close();
in.close();
} catch (FileNotFoundException e){
System.out.println("File does not exist or could not be found");
System.err.println("FileNotFoundException: "+ e.getMessage());
} catch (IOException e){
System.out.println("Problem reading file");
System.err.println("IOException: " + e.getMessage());
}
}
}
Logic:
Create a separate holder for the attributes you want to have the sorting on.
Apply Comparator on that Person object.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MultiKey {
public static void main(String[] args) {
File textFile = new File("H:\\Names_ages.txt");
FileReader in;
BufferedReader readFile;
String lineOfText;
try {
in = new FileReader(textFile);
readFile = new BufferedReader(in);
BufferedReader reader = new BufferedReader(new FileReader(textFile));
List<Person> results = new ArrayList<Person>();
while ((lineOfText = readFile.readLine()) != null) {
//split here the line into name and age separate variables basedon delimiter available between them.
Person p = new Person(name,age);
results.add(p);
}
order(results);
System.out.println(results);
readFile.close();
in.close();
} catch (FileNotFoundException e){
System.out.println("File does not exist or could not be found");
System.err.println("FileNotFoundException: "+ e.getMessage());
} catch (IOException e){
System.out.println("Problem reading file");
System.err.println("IOException: " + e.getMessage());
}
}
}
private static void order(List<Person> persons) {
Collections.sort(persons, new Comparator<Person>() {
public int compare(Object o1, Object o2) {
String x1 = ((Person) o1).getName();
String x2 = ((Person) o2).getName();
int sComp = x1.compareTo(x2);
if (sComp != 0) {
return sComp;
} else {
Integer x1 = ((Person) o1).getAge();
Integer x2 = ((Person) o2).getAge();
return x1.compareTo(x2);
}
}});
}
public class Person{
private String name;
private int age;
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public int getAge(){
return this.age;
}
public vois setAge(int age){
this.age = age;
}
}
Typical Approach would be:
Parse each line and create an encapsulation object for it
(in your example a class "Person" with two fields for "name" and "age")
How you do this parsing depends on the format of the lines in the file
e.g. you can use String.split(",") for this, if the values in the line
are separated by comma.
Add the encapsulation objects to a list and then e.g. sort using
a Comparator. Use java.util.Collections.sort(Comparator).
Of course, with that list of encapsulation objects you can do much more very easily, e.g. find Persons with same Name but different Ages.
You can use the thenComparing to chain Comparators
Comparator<String> byName = Comparator.comparing(s -> s.split(" ")[0]);
Comparator<String> byAge = Comparator.comparingInt(s -> Integer.parseInt(s.split(" ")[1]));
try (BufferedReader br = new BufferedReader(new FileReader("filePath"))) {
List<String> sorted = br.lines().sorted(byName.thenComparing(byAge)).collect(Collectors.toList());
return sorted;
} catch (IOException e) {
e.printStackTrace();
}
If more than one space also expected try pattern \\s+ instead of white space
or we can create a Comparator like below instead of creating two Comparators
Comparator<String> c = Comparator.<String, String> comparing(s -> s.split("\\s+")[0])
.thenComparingInt(s -> Integer.parseInt(s.split("\\s+")[1]));
I am trying to write a program that will allow a user to input a name of a movie and the program would then generate the date associated with. I have a text file that has date and the movies that pertain to it. I am reading the file via Scanner and I created a movie class that stores an ArrayList and String for movies and date, respectively. I am having trouble with reading the files. Can anyone please assist me. Thank you!
Here is a part of the text file:
10/1/2014
Der Anstandige
"Men, Women and Children"
Nas: Time is Illmatic
10/2/2014
Bang Bang
Haider
10/3/2014
Annabelle
Bitter Honey
Breakup Buddies
La chambre bleue
Drive Hard
Gone Girl
The Good Lie
A Good Marriage
The Hero of Color City
Inner Demons
Left Behind
Libertador
The Supreme Price
Here is my movie class
import java.util.ArrayList;
public class movie
{
private ArrayList<String> movies;
private String date;
public movie(ArrayList<String> movies, String date)
{
this.movies = movies;
this.date = date;
}
public String getDate()
{
return date;
}
public void setDate(String date)
{
this.date = date;
}
public ArrayList<String> getMovies()
{
return movies;
}
}
Here is the readFile class
package Read;
import java.util.List;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class readFile
{
public static List<movie> movies;
public static String realPath;
public static ArrayList<String> mov;
public static String j;
public static String i;
public static void main(String[]args)
{
//movies = new ArrayList<movie>();
realPath = "movie_release_dates.txt";
File f = new File(realPath);
try
{
String regex1 = "[^(0-9).+]";
String regex2 = "[^0-9$]";
Scanner sc = new Scanner(f);
while (sc.hasNextLine())
{
System.out.println("Hello");
//movies
if(!sc.nextLine().matches(regex2))
{
i = sc.nextLine();
System.out.println("Hello2");
System.out.println(i);
}
//date
while(sc.nextLine().matches(regex1))
{
System.out.println("Hello3");
if(!sc.nextLine().matches(regex1))
{
j = sc.nextLine();
mov.add(sc.nextLine());
System.out.println("Hello4");
}
}
movie movie = new movie(mov,i);
movies.add(movie);
}
// sc.close();
}
catch(Exception e)
{
System.out.println("CANT");
}
}
}
You shouldn't be calling sc.nextLine () in every check. Every NextLine () call reads next line.This means that you are checking one line and processing next line
package com.stackoverflow.q26269799;
import java.util.List;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadFile {
public static List<Movie> movies = new ArrayList<Movie>();
public static String realPath;
public static ArrayList<String> mov;
public static String j;
public static String i;
public static void main(String[] args) {
//movies = new ArrayList<movie>();
realPath = "movie_release_dates.txt";
File f = new File(realPath);
if ( !f.exists()) {
System.err.println("file path not specified");
}
try {
String regex1 = "[^(0-9).+]";
String regex2 = "[^0-9$]";
Scanner sc = new Scanner(f);
while (sc.hasNextLine()) {
System.out.println("Hello");
// movies
String nextLine = sc.nextLine();
if (nextLine != null) {
if ( !nextLine.matches(regex2)) {
i = nextLine;
System.out.println("Hello2");
System.out.println(i);
}
// date
while (nextLine != null && nextLine.matches(regex1)) {
System.out.println("Hello3");
if ( !nextLine.matches(regex1)) {
j = nextLine;
mov.add(nextLine);
System.out.println("Hello4");
}
nextLine = sc.nextLine();
}
}
Movie movie = new Movie(mov, i);
movies.add(movie);
}
// sc.close();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
This is needed: //movies = new ArrayList<movie>();
Every time you call nextLine it will move the scanner point to the next line. So call it once a time and check if it match those regex. String nextLine = sc.nextLine();
Please check you whether the file path is specified.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class ReadFile
{
Map<String, String> movies;
public static void main(String[] args) throws IOException
{
ReadFile readFile = new ReadFile();
readFile.movies = new TreeMap<>();
try
{
readFile.importData();
printf(readFile.queryData("Der Anstandige"));
printf(readFile.queryData("Bitter"));
printf(readFile.queryData("blah"));
printf(readFile.queryData("the"));
}
catch(IOException e)
{
throw(e);
}
}
void importData() throws IOException, FileNotFoundException
{
LineNumberReader reader = null;
File file = new File("c:/movie_release_dates.txt");
try
{
reader = new LineNumberReader(new FileReader(file), 1024*64); //
String line;
String date = null, movie = null;
while((line = reader.readLine()) != null)
{
line = line.trim();
if(line.equals("")) continue;
if(line.matches(PATTERN_DATE))
{
date = line;
date = strf("%s/%s",
date.substring(date.length() - 4),
date.substring(0, date.length() - 5));
continue;
}
else
{
movie = line.trim();
}
movies.put(movie, date);
}
}
catch(FileNotFoundException e)
{
throw(e);
}
finally
{
reader.close();
}
}
String queryData(String title)
{
String regex = "(?i)" + title.replaceAll("\\s", "\\s+");
String[] matches = new String[movies.size()];
int i = 0; for(Entry<String , String> movie : movies.entrySet())
{
String key = movie.getKey();
String val = movie.getValue();
if(key.matches(regex))
{
matches[i++] = strf("{movie=%s, date=%s}", key, val);
}
else if(key.toUpperCase().trim()
.contains(title.toUpperCase().trim()))
{
matches[i++] = strf("{movie=%s, date=%s}", key, val);
}
}
String string = "";
if(matches[0] == null)
{
string = "Not found\n";
}
else
{
i = 0; while(matches[i] != null)
{
string += matches[i++] + "\n";
}
}
return string;
}
final String strf(String arg0, Object ... arg1)
{
return String.format(arg0, arg1);
}
final static void printf(String format, Object ... args)
{
System.out.printf(format, args);
}
final static void println(String x)
{
System.out.println(x);
}
final String PATTERN_DATE = "\\d{1,2}\\/\\d{1,2}\\/\\d{4}";
}
Console output:
{movie=Der Anstandige, date=2014/10/1}
{movie=Bitter Honey, date=2014/10/3}
Not found
{movie=The Good Lie, date=2014/10/3}
{movie=The Hero of Color City, date=2014/10/3}
{movie=The Supreme Price, date=2014/10/3}
How to run two classes in which one gives some data in a textfile & the other should take that file and process it?
I have two Java files. File1 processes something and outputs a text file. File2 should take that text file and process it to create a final output.
My requirement is to have two independent java files that work together.
File1
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Map;
import java.util.TreeMap;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
public class FlatFileParser
{
public static void main(String[] args)
{
try
{
// The stream we're reading from
BufferedReader in;
List<String> ls = new ArrayList<String>();
BufferedWriter out1 = new BufferedWriter(new FileWriter("inValues.txt" , true ));
BufferedReader out11 = new BufferedReader(new FileReader("inValues.txt"));
// Return value of next call to next()
String nextline;
String line="";
if (args[0].equals("1"))
{
in = new BufferedReader(new FileReader(args[1]));
nextline = in.readLine();
while(nextline != null)
{
nextline = nextline.replaceAll("\\<packet","\n<packet");
System.out.println(nextline);
nextline = in.readLine();
}
in.close();
}
else
{
in = new BufferedReader(new FileReader(args[1]));
nextline = in.readLine();
HashMap<String,String> inout = new HashMap<String,String>();
while(nextline != null)
{
try
{
if (nextline.indexOf("timetracker")>0)
{
String from = "";
String indate = "";
if (nextline.indexOf("of in")>0)
{
int posfrom = nextline.indexOf("from");
int posnextAt = nextline.indexOf("#", posfrom);
int posts = nextline.indexOf("timestamp");
from = nextline.substring(posfrom+5,posnextAt);
indate = nextline.substring(posts+11, posts+23);
String dd = indate.split(" ")[1];
String key = dd+"-"+from+"-"+indate;
//String key = from+"-"+indate;
String intime = "-in-"+nextline.substring(posts+24, posts+35);
inout.put(key, intime);
}
else if (nextline.indexOf("of out")>0)
{
int posfrom = nextline.indexOf("from");
int posnextAt = nextline.indexOf("#", posfrom);
int posts = nextline.indexOf("timestamp");
from = nextline.substring(posfrom+5,posnextAt);
indate = nextline.substring(posts+11, posts+23);
String dd = indate.split(" ")[1];
String key = dd+"-"+from+"-"+indate;
String outtime = "-out-"+nextline.substring(posts+24, posts+35);
if (inout.containsKey(key))
{
String val = inout.get(key);
if (!(val.indexOf("out")>0))
inout.put(key, val+outtime);
}
else
{
inout.put(key, outtime);
}
}
}
}
catch(Exception e)
{
System.err.println(nextline);
System.err.println(e.getMessage());
}
nextline = in.readLine();
}
in.close();
for(String key: inout.keySet())
{
String val = inout.get(key);
out1.write(key+" , "+val+"\n");
}
out1.close();
}
}
catch (IOException e)
{
throw new IllegalArgumentException(e);
}
}
File2
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.io.FileReader;
public class RecordParser
{
private static BufferedReader reader;
private List<Person> resource;
private List<String> finalRecords;
public RecordParser(BufferedReader reader)
{
this.reader = reader;
this.resource = new ArrayList<Person>();
this.finalRecords = new ArrayList<String>();
}
public void execute() throws IOException
{
String line = null;
while ((line = reader.readLine()) != null)
{
String[] parts = line.split(" , ");
addPerson(new Person(parts[0]));
if ((parts[1].contains("-in-")) && (parts[1].contains("-out-")))
{
String[] inout = parts[1].split("-out-");
Person person = getPerson(parts[0]);
person.setInTime(inout[0]);
person.setOutTime("-out-" + inout[1]);
}
else if (parts[1].contains("-in-"))
{
Person person = getPerson(parts[0]);
person.setInTime(parts[1]);
}
else
{
Person person = getPerson(parts[0]);
person.setOutTime(parts[1]);
}
}
// finalRecords the resource to the String list
for (Person p : resource)
{
finalRecords.add(p.getPerson());
}
}
private void addPerson(Person person)
{
for (Person p : resource)
{
if (p.getNameDate().equals(person.getNameDate()))
{
return;
}
}
resource.add(person);
}
private Person getPerson(String nameDate)
{
for (Person p : resource)
{
if (p.getNameDate().equals(nameDate))
{
return p;
}
}
return null;
}
public List<String> getfinalRecords()
{
return finalRecords;
}
public static void main(String[] args)
{
try {
BufferedReader reader = new BufferedReader(new FileReader("sample.txt"));
RecordParser recordParser = new RecordParser(reader);
recordParser.execute();
for (String s : recordParser.getfinalRecords())
{
System.out.println(s);
}
reader.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
public class Person
{
private String nameDate;
private String inTime;
private String outTime;
public Person (String nameDate)
{
this.nameDate = nameDate;
this.inTime = "missing in";
this.outTime = "missing out";
}
public void setInTime(String inTime)
{
this.inTime = inTime;
}
public void setOutTime(String outTime)
{
this.outTime = outTime;
}
public String getNameDate()
{
return nameDate;
}
public String getPerson()
{
StringBuilder builder = new StringBuilder();
builder.append(nameDate);
builder.append(" , ");
builder.append(inTime);
builder.append(" , ");
builder.append(outTime);
return builder.toString();
}
}
}
I want to be able to import the values from inValues.txt (created in File1) and process them in File2.
Create a batch/sh file and run one java program after the other. If you want to pass the file details to the second program you can do that by providing a run time argument.
on windows:
java -classpath .;yourjars FlatFileParser
java -classpath .;yourjars RecordParser {optionalfiledetails}
on linux
java -classpath .:yourjars FlatFileParser
java -classpath .:yourjars RecordParser {optionalfiledetails}