Complicated .txt file Parsing Android Studio - java

I need to parse a text file in the form:
Encanto, 6/101-105, 7/320-322
Flora, 1/2-5
Vista, 7/67-70
WORK ORDER
I know how to parse a .txt file that has lines in the form "name, number" into two separate ArrayLists using the following method:
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while( (line = bufferedReader.readLine()) != null){
allNames.add(line.split(", ")[0]);
allNums.add(Integer.parseInt(line.split(",\\s+")[1]));
}
bufferedReader.close();
Now I must get the Lists to have these items:
ArrayList<String> names = {"Encanto", "Flora", "Vista", "WORK ORDER"};
ArrayList<String> lots = {"Bld.6 101", "Bld.6 102", "Bld.6 103", "Bld.6 104", "Bld.6 105", "Bld.7 320", "Bld.7 321", "Bld.7 322"};
ArrayList<String> lots1 = {"Bld.1 2", "Bld.1 3", "Bld.1 4", "Bld.1 5",};
ArrayList<String> lots2 = {"Bld.7 67", "Bld.7 68", "Bld.7 69", "Bld.7 70"};

Create this Parser class
class Parser {
String parseName(String line) {
String[] blocks = line.split(", ");
if (blocks.length > 0) {
return blocks[0];
}
return null;
}
List<String> getLots(String line) {
List<String> lotList = new ArrayList<>();
String[] blocks = line.split(", ");
for (String block : blocks) {
// I suppose that lot line will always have "/" and "-"
if (block.contains("/") && block.contains("-")) {
lotList.addAll(generateLots(block));
}
}
return lotList;
}
private List<String> generateLots(String block) {
List<String> lots = new ArrayList<>();
String prefix = "Bld.";
String bldNumber = block.substring(0, block.indexOf("/"));
int lowest = Integer.parseInt(block.substring(block.indexOf("/") + 1, block.indexOf("-")));
int highest = Integer.parseInt(block.substring(block.indexOf("-") + 1, block.length()));
for (int i = lowest; i <= highest; i++) {
lots.add(prefix + bldNumber + " " + i);
}
return lots;
}
}
Then use it in your code
// create a new Parser object
Parser parser = new Parser();
// get name
System.out.println(parser.parseName(line));
// get lots
List<String> lotList = parser.getLots(line);
for (String lot : lotList) {
System.out.println(lot);
}
=========================================================
Edit:
To answer your comment, you can create lot lists on the fly. If I refer to your question, it will be like this
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
Parser parser = new Parser();
List<String> names = new ArrayList<>();
List<List<String>> lotsList = new ArrayList<>();
while ((line = bufferedReader.readLine()) != null) {
names.add(parser.parseName(line));
lotsList.add(parser.getLots(line));
}
bufferedReader.close();

Related

Sorting a Java String Array with a pattern

I am currently reading and writing to a text file and I cant figure out a way to sort. I thought I would be able to sort by pattern. I would like to sort a java string array by the pattern (0-9, A-Z, a-z). Basically I would like to ignore non-alphanumeric characters, sort with numbers preceding letters, and capital letters preceding lowercase letters (i.e., 0-9, A-Z, a-z). I would like to remove lines that only have non-alphanumeric characters.
File f1 = new File(fp);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
count++;
// SORT GOES HERE
if (line.contains(sx)) {
line = line.replace(line, "");
}
if (yint > 0 && !line.isBlank()) {
line = line.substring(yint);
}
if(!line.isBlank()){
line = line.replace(line, count + " " + line + "\n");
lines.add(line);
} else {
lines.add(line);
}
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
I would likely use something like Collections.sort() at the end and a simple check in the loop:
File f1 = new File(fp);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
count++;
if (!line.matches("[a-zA-Z0-9]+")) {
continue;
}
if (line.contains(sx)) {
line = line.replace(line, "");
}
if (yint > 0 && !line.isBlank()) {
line = line.substring(yint);
}
if(!line.isBlank()){
line = line.replace(line, count + " " + line + "\n");
lines.add(line);
} else {
lines.add(line);
}
}
fr.close();
br.close();
Collections.sort(lines, (a, b) -> {
String aNum = a.replaceAll("[^a-zA-Z0-9]", "");
String bNum = b.replaceAll("[^a-zA-Z0-9]", "");
return a.compareTo(b);
});
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
EDIT: You can certainly make this work faster/better by quick-checking perhaps in the sort, etc - but generally this is the idea I think
You can't sort the file while you are reading it, in your case it needs to be done before:
// Sort the file
Path initialFile = Paths.get("myFile.txt");
List<String> sortedLines = Files.lines(initialFile)
.sorted()
.collect(Collectors.toList());
// Process the sorted lines
List<String> lines = new ArrayList<String>();
int count=0;
for(String line : sortedLines) {
System.out.println("l: "+line);
count++;
if (line.contains(sx)) {
line = line.replace(line, "");
}
if (yint > 0 && !line.isEmpty()) {
line = line.substring(yint);
}
if (!line.isEmpty()) {
System.out.println("line:"+line);
line = line.replace(line, count + " " + line + "\n");
System.out.println("new line:"+line);
lines.add(line);
} else {
System.out.println("add:"+line);
lines.add(line);
}
}
// Write output file
File f1 = new File("myFile.txt");
try(BufferedWriter out = new BufferedWriter( new FileWriter(f1))){
for (String s : lines)
out.write(s);
}
Try this.
static void sortByAlphaNumeric(String inFile, String outFile) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(inFile)).stream()
.map(line -> new Object() {
String sortKey = line.replaceAll("[^0-9A-Za-z]", "");
String originalLine = line;
})
.filter(obj -> !obj.sortKey.equals(""))
.sorted(Comparator.comparing(obj -> obj.sortKey))
.map(obj -> obj.originalLine)
.collect(Collectors.toList());
Files.write(Paths.get(outFile), lines);
}

CSV date into arraylist_Java

CSV file
I am trying to save data separately by using ArrayList.
However, after saving one data into the array, it skips one line then saves the data. Please help me with this problem.
private void readCSVFile(String tickerCode, File file) {
System.out.println("Reading file " + tickerCode);
System.out.println(file.getPath());
try {
ArrayList<List<String>> line = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(file));
CSVReaderHeaderAware csvReader = new CSVReaderHeaderAware(br);
int numLine = 0;
String[] values;
while ((values = csvReader.readNext()) != null) {
ArrayList<String> data = new ArrayList<>();
data.add(values[0]);
data.add(values[1]);
data.add(values[2]);
data.add(values[3]);
data.add(values[4]);
data.add(values[5]);
data.add(values[6]);
line.add(data);
if(numLine == 0){
System.out.print("StartDate = "+ values[0]);
}
if((csvReader.readNext() == null)){
System.out.println(" EndDate = " + values[0]);
}
++numLine;
}
debugger variable
As mentioned in a comment, you cannot use csvReader.readNext() inside the loop as well to check if the next element is null, because it will actually read the next line. So what you can do is keep the last processed row's date in a variable, and then print it as the EndDate after the while loop is finished.
ArrayList<List<String>> line = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(file));
CSVReaderHeaderAware csvReader = new CSVReaderHeaderAware(br);
int numLine = 0;
String[] values;
String endDate = null;
while ((values = csvReader.readNext()) != null) {
ArrayList<String> data = new ArrayList<>();
data.add(values[0]);
data.add(values[1]);
data.add(values[2]);
data.add(values[3]);
data.add(values[4]);
data.add(values[5]);
data.add(values[6]);
line.add(data);
if(numLine == 0){
System.out.print("StartDate = "+ values[0]);
}
endDate = values[0];
++numLine;
}
if (endDate != null) { // Need to check null in case your CSV didn't have any rows
System.out.println(" EndDate = " + endDate);
}

Java Code check fields in duplicate, when value change start again

I want to write small java program to read data file first field and add seqcution number
Input file:
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Output file should be:
robert,190 vikign,...,0
robert,2401 windy,...,1
robert,1555 oakbrook,...,2
michell,2524 sprint,...,0
michell,1245 oakbrrok,...,1
xyz,2455 xyz drive,....,0
Check first field when value change sequction number start back to 0 otherwise add sequction number by 1
here is my code:
public static void createseq(String str) {
try {
BufferedReader br = null;
BufferedWriter bfAllBWP = null;
File folderall = new File("Sort_Data_File_Out");
File[] BFFileall = folderall.listFiles();
for (File file : BFFileall) {
br = new BufferedReader(new FileReader(file));
String bwp = "FinalDataFileOut\\" + str;
bfAllBWP = new BufferedWriter(new FileWriter(bwp));
String line;
line = br.readLine();
String[] actionID = line.split("\\|");
String fullname = actionID[0].trim();
int seq = 0;
String fullnameb;
while ((line = br.readLine()) != null) {
actionID = line.split("\\|");
fullnameb = actionID[0].trim();
if(fullname.equals(fullnameb)) {
seq++;
}
else {
System.out.println(line + "======" + seq + "\n");
seq = 0;
fullname = fullnameb;
}
System.out.println("dshgfsdj "+line + "======" + seq + "\n");
}
}
}
catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
The below code will fix the issue.I have updated the code if you face any pblm plz let me know :
Input :
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Code :
public static void createseq() {
try {
File file = new File("d:\\words.txt"); //Hardcoded file for testing locally
BufferedReader br = new BufferedReader(new FileReader(file));
HashMap<String,Integer> counter = new HashMap<String, Integer>();
String line;
while((line = br.readLine())!= null)
{
String[] actionID = line.split(",");
String firstName = actionID[0];
if(counter.containsKey(firstName))
{
counter.put(firstName, counter.get(firstName) + 1);
}
else
{
counter.put(firstName,0);
}
System.out.println(line+" "+counter.get(firstName));
}
br.close();
} catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
Ouput Come :
robert,190 vikign,... 0
robert,2401 windy,... 1
robert,1555 oakbrook,... 2
michell,2524 sprint,... 0
michell,1245 oakbrrok,... 1
xyz,2455 xyz drive,.... 0

tokenized output into an array from string

i am working on netbeans...i need to read a file and tokenize then and store it in an array for my future operations....i have attached the code where the line5 contains the tokens...while converting into array iam getting error as
Exception :
" Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1000
at preprocess.mainpage.jButton2ActionPerformed(mainpage.java:224)
at preprocess.mainpage.access$100(mainpage.java:18)
at preprocess.mainpage$2.actionPerformed(mainpage.java:62)"
Code:
int counter=-1;
int n=0;
String[] arr = new String[1000];
try
{
BufferedReader b = new BufferedReader(new FileReader("C:/Users/sky/Documents/NetBeansProjects/Preprocess/src/preprocess/cdr1.txt"));
String line;
while ((line = b.readLine()) != null)
{
counter+=1;
StringTokenizer st2 = new StringTokenizer(line, " ");
String line5 = (String) st2.nextElement();
arr[n] = line5;
n++;
}
}
catch (Exception e)
{
}
ArrayIndexOutOfBoundsException because may be your array size is less. So better use ArrayList like following:
int counter=-1;
int n=0;
//String[] arr = new String[1000];
List<String> list = new ArrayList<String>(); // Create ArrayList
try{
BufferedReader b = new BufferedReader(new FileReader("C:/Users/sky/Documents/NetBeansProjects/Preprocess/src/preprocess/cdr1.txt"));
String line;
while ((line = b.readLine()) != null) {
counter+=1;
StringTokenizer st2 = new StringTokenizer(line, " ");
String line5 = (String) st2.nextElement();
//arr[n] = line5;
//n++;
list.add(line5); // Add you string into list
}
String[] aa = list.toArray(new String[0]); // convert list into String of array if you need it
}
catch (Exception e){
}

How to split text file based on startswith

I want to split file as Header with detail in a list based on sequence.
want to split the text file using Header and detail I tried something like this but doesn't help.
I wanted to call previous iteration of iterator but I couldn't...
File :
H>>>>>>
L>>>>>>>
L>>>>>>>
L>>>>>>>
H>>>>>>>
L>>>>>>>
L>>>>>>>
H>>>>>>>
L>>>>>>> ...
I wanted :
List 1 with H , L , L ,L
List 2 with H , L , L
List 3 with H , L
Code Tried :
List<String> poString = new ArrayList<String>();
if(poString !=null && poString.size() > 0)
{
ListIterator<String> iter = poString.listIterator();
while(iter.hasNext())
{
String tempHead = iter.next();
List<String> detailLst = new ArrayList<String>();
if(tempHead.startsWith("H"))
{
while(iter.hasNext())
{
String detailt = iter.next();
if(!detailt.startsWith("H"))
detailLst.add(detailt);
else
{
iter.previousIndex();
}
}
}
}
Try this (untested):
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
List<StringBuilder> myList = new List<StringBuilder>();
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if (line[0] == 'H')
{
myList.add(sb);
sb = new StringBuilder();
}
sb.append(line[0]);
line = br.readLine();
}
} finally {
br.close();
}
as far as I understood, eventually how many H..lines in your file, how many List<String> would you want to have.
If you don't know the exact number, (in your example, it is 3) then you have a List of List (List<List<String>>).
//read the file, omitted
List<List<String>> myList = new ArrayList<<List<String>>();
List<String> lines = null;
boolean createList = false;
while (line != null) {
if (line.startsWith("H")){
myList.add(lines);
lines = new ArrayList<String>();
}
//if the 1st line of your file not starting with 'H', NPE, you have to handle it
lines.add(line);
line=readnextlineSomeHow(); //read next line
}
the above codes may not work out of box, but it gives you the idea.
Try this, I've tried a little on my own and it works
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
ArrayList<ArrayList<String>> result = new ArrayList<> ();
int numlines =0;
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if (line.startsWith("H"))
{
result.add(new ArrayList<String>());
result.get(numlines).add("H");
line = br.readLine();
while(line != null && !line.startsWith("H")){
if(line.startsWith("L")) result.get(numlines).add("L");
line = br.readLine();
}
++numlines;
}
else line = br.readLine();
}
} finally {
br.close();
}
You can use this..
public static void main(String a[]) throws Exception
{
ArrayList<String> headers=new ArrayList();
ArrayList<String> lines=new ArrayList();
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
File f= new File("inputfile.txt");
Scanner scanner = new Scanner(f);
try {
while (scanner.hasNextLine()){
String ss=scanner.nextLine();
String key= String.valueOf(ss.charAt(0));
if ( map.containsKey(key))
{
ArrayList<String> temp=(ArrayList) map.get(key);
temp.add(ss);
map.put(key, temp);
}
else
{
ArrayList<String> temp= new ArrayList();
temp.add(ss);
map.put(key, temp);
}
}
}
catch(Exception e)
{
throw e;
}
}

Categories

Resources