How can I count these values? - java

I have a DB that usually generates a file with 3000 lines, actually I want to count the number of LAYERID(s)
My DB file is like this :
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE BUTYP=ACB8T,RAAT=FALSE,GBPATH=AAP4,GTXT=12;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_01,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_01,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_02,USFGN=DISABLED;
CREATE BUTYP=ACB9T,RAAT=TRUE,GBPATH=AAP4,GTXT=32;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_01,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_02,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_03,USFGN=DISABLED;
CREATE TRMD=GFT,LAYID=LY_03,USFGN=DISABLED;
CREATE BUTYP=ACB2T,RAAT=TRUE,GBPATH=AAP4,GTXT=1;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE BUTYP=ACB8T,RAAT=FALSE,GBPATH=AAP4,GTXT=2;
CREATE TRMD=GFT,LAYID=LY_00,USFGN=DISABLED;
CREATE BUTYP=ACB8T,RAAT=TRUE,GBPATH=AAP4,GTXT=3;
if we just have "LAYID=LY_00" (like the first line) we must ignore it, but if under the "LAYID=LY_00" be "LAYID=LY_01 and ..." (like the third line) we must count "LAYID=LY_00" and others layerids,for example in line 3 till line 6 we have 4 Layeids
LAYID=LY_00
LAYID=LY_01
LAYID=LY_01
LAYID=LY_02
So count is 4 and if we want to count all of them we have 9, As I said before, if we just have
LAYID=LY_00 simillar line 1 we ignore it.
Also I wrote this method for read line by line :
public void execToken(File f) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
StringTokenizer strt = new StringTokenizer(line, ";");
while (strt.hasMoreTokens()) {
String token = strt.nextToken();
layerSupport(token);
}
}
}
and, I know the below method is not true and complete yet, but it's maybe useful for you
public void layerSupport(String token){
if(token.startsWith("CREATE TRMD") && !token.contains("LAYID=LY_00"))
System.out.println(token) ;
}
many thanks for your help ...

public int execToken(File f) throws Exception
{
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
int count = 0;
Pattern layID = Pattern.compile("LAYID=LY_\\d+");
Matcher matcher = null;
boolean isSingle = true;
while ((line = br.readLine()) != null)
{
if(line.contains("LAYID=LY_00"))
{
isSingle = false;
continue;
}
matcher = layID.matcher(line);
if(matcher.find())
{
count++;
if(!isSingle)
count++;
}
isSingle = true;
}
return count;
}
try this.it remembers if previous line contains LAYID=LY_00 and increments count twice in next iteration, if LAYID=LY_<digits> was found and isSingle is false.

Something like that:
public int execToken(File f) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(f));
int count = 0;
String line;
String previousLine = "";
while ((line = br.readLine()) != null) {
if (line.startsWith("CREATE TRMD")) {
if (!previousLine.isEmpty()) {
count += (previousLine.contains("LAYID=LY_00") ? 2 : 1);
}
previousLine = line;
} else {
previousLine = "";
}
}
return count;
}
Not tested.

Related

How to check if a string in a text file is correct

I have a text file and I need to check if it is correct. The file should be of the type:
XYab
XYab
XYab
Where X,Y,a,b can take only a certain range of value. For example b must be a value between 1 and 8. These values are defined by 4 enum (1 enum for X,1 enum for Y, etc..). The only thing that came to my mind is something like this:
BufferedReader br = new BufferedReader(new FileReader(FILENAME)
String s;
while ((s = br.readLine()) != null) {
if(s.charAt(0)==Enum.example.asChar())
}
But of course it checks only the first line of the file. Any advice on how I can check all the file's lines?
You could try something like this, (modify it according to yours enums)
#Test
public void findDates() {
File file = new File("pathToFile");
try{
Assert.assertTrue(validateFile(file));
}catch(Exception ex){
ex.printStackTrace();
}
}
private boolean validateFile(File file) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
// add yours enumns to one list
List<Enum> enums = new ArrayList<>();
enums.add(EnumX);
enums.add(EnumY);
enums.add(EnumA);
enums.add(EnumB);
while ((line = br.readLine()) != null) {
// process the line.
if(line.length() > 4){
return false;
}
//for each position check if the value is valid for the enum
for(int i = 0; i < 4; i++){
if(enums.get(i)).valueOf(line.charAt(i)) == null){
return false;
}
}
}
return true;
}
Don't forget about collision but if you have number or string you can use the regexp to do that.
On each Enum you have to do a function regexp like this. You can use an external Helper instead.
enum EnumX {
A,B,C,D, ...;
...
// you enum start to 0
public static String regexp(){
return "[0-" + EnumX.values().length +"]";
}
}
// it is working also if you have string in your file
enum EnumY{
A("toto"),B("titi"),C("tata"),D("loto");
public static String regexp(){
StringBuilder regexp = new StringBuilder("[");
for(EnumY value : EnumY.values()){
regexp.append(value).append(",");
}
regexp.replace(regexp.length()-1, regexp.length(), "]");
return regexp.toString();
}
}
public boolean isCorrect(File file){
// build the regexp
String regexp = EnumX.regexp() + EnumY.regexp() + EnumA.regexp() +EnumB.regexp();
// read the file
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
if (line.matches(regexp) == false){
// this line is not correct
return false;
}
}
return true;
}

Count the lines of several methods but return separate values not the sum of all

I'm going to elabortate my question because I had a hard time labeling the question the right way.
I'm labeling my methods like this:
/*Start*/
public void contadorDeLineas(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
/*Finish*/
I have several methods labeled like that but I want to count them separately, but the code I wrote counts the lines inside the methods starting from public and finishing in "Finish". But as for now the code I wrote counts all the lines inside the methods and return the sum of all the lines. What I want to do is read the first block return that value and continue searching for the next block of code.
This is the code I wrote
public void LinesMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int lines_inside = 0;
while((line = br.readLine())!=null){
if(line.startsWith("/*St")){
do{
line = br.readLine();
line = line.trim();
System.out.println(line);
if(!(line.equals("") || line.startsWith("/*"))){
lines_inside++;
}
}while(!line.startsWith("/*Fi"));
}
}
br.close();
System.out.println("Found: " + lines_inside);
}
This is an example of what my code is showing in the console
/*Start*/
public void LineMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
/*Finish*/
/*Start*/
public static void main(String[] args)throws IOException{
program2 test = new program2();
File root = new File(args[0]);
test.LOC(root);
System.out.println("Found: " + test.lines);
System.out.println("Other type of lines: " + test.toDo);
}
}
/*Finish*/
Block comments lines: 11
Instead I'm looking for a result like a first print showing the number 3 and then a number 8.
Any guidance will be appreciated.
Try this
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
boolean inside = false;
int count = 0;
String line;
while ((line = br.readLine()) != null) {
if (line.contains("/*Start*/")) {
inside = true;
count = 0;
} else if (line.contains("/*Finish*/")) {
System.out.println("Found: " + count);
inside = false;
} else if (inside) {
++count;
}
}
if (inside && count > 0)
System.out.println("Found: " + count);
}
if you have several methods printing out all the lines may be to much when you are only interested in the number of lines. You can put the names of the methods and the number of lines in a map and print that out.
public static void LinesMethods(File file)throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int lines_inside = 0;
Map<String, Integer> map = new HashMap<>();
while((line = br.readLine())!=null){
lines_inside = 0;
if(line.startsWith("/*St")){
String method = "";
do{
line = br.readLine();
if(line.contains("public")){
method = line.substring(0, ine.indexOf('('));
}
line = line.trim();
if(!(line.equals("") || line.startsWith("/*"))){
lines_inside++;
}
}while(!line.startsWith("/*Fi"));
map.put(method, lines_inside);
}
}
br.close();
for(String s :map.keySet()){
System.out.println(s +" : "+ map.get(s));
}
}
Try to put lines_inside++; in the code like this:
while((line = br.readLine())!=null){
lines_inside++;
...
This gives you the rught number of elements in file.

mark & reset in java BufferedReader

I want to use mark() and reset() method to read the line before divider.
String line;
FileReader fr = new FileReader(PATH);
LineNumberReader br = new LineNumberReader(fr);
String DIVIDER = "================================";
while ((line = br.readLine()) != null) {
boolean endOfObj = false;
while (!line.trim().contains(DIVIDER)) {
br.mark(line.length());
line = br.readLine(); //return next line
}
br.reset();
line = br.readLine();
but line variable value is not the previous line of divider.
what is my problem is .
thank you
Could you try using the following code? I tidied up your code a bit, and put it into a method called getPreviousLine(). I got the feeling that you were getting hung up on using mark() and reset(), so I just relied on pure logic and state to find the line before the divider. If no divider is found, the method will return null.
String getPreviousLine(String PATH) {
String line;
FileReader fr = new FileReader(PATH);
LineNumberReader br = new LineNumberReader(fr);
String DIVIDER = "================================";
boolean endOfObj = false;
String previousLine = br.readLine();
if (previousLine == null) {
return null;
}
while ((line = br.readLine()) != null) {
if (line.trim().contains(DIVIDER)) {
endOfObj = true; // found the divider; break
break;
} else {
previousLine = line; // advance your line pointer
}
}
if (endOfObj) {
return previousLine;
} else {
return null;
}
}

Read text file line by line and store in a class?

I need some help with reading line by line from a file then put it into a class.
My idea is like this: I've saved everything in a text file, it's about 500 lines but this can change that's why I wan't the line number reader and then lnr/5 to get how many times I'll need to run the for loop. I wan't it to first take line 1,2,3,4,5 into a object, then 6,7,8,9,10 and so on. So basically I need each 5 lines go in seperatley.
Code:
public static void g_txt() {
LineNumberReader lnr;
String[] text_array = new String[500];
int nu = 0;
try {
lnr = new LineNumberReader(new FileReader(new File("test.txt")));
lnr.skip(Long.MAX_VALUE);
//System.out.println(lnr.getLineNumber());
lnr.close();
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
text_array[nu] = line;
nu++;
}
} catch (IOException e) {
}
}
as you can see, I now has it in an array. Now I need it to make so 1,2,3,4,5 and so on go in to this:
filmer[antalfilmer] = new FilmSvDe(line1);
filmer[antalfilmer].s_filmbolag(line2);
filmer[antalfilmer].s_producent(line3);
filmer[antalfilmer].s_tid(line4);
filmer[antalfilmer].s_betyg(line5);
filmer[antalfilmer].s_titel(line1);
then antalfilmer++.
public static void g_txt() {
String[] text_array = new String[5];
int nu = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
text_array[nu] = line;
nu++;
if (nu == 5) {
nu = 0;
makeObject(text_array);
}
}
} catch (IOException e) {
}
}
private static void makeObject(String[] text_array) {
// do your object creation here
System.out.println("_________________________________________________");
for (String string : text_array) {
System.out.println(string);
}
System.out.println("_________________________________________________");
}
Try this.

How to Print Object Line by line

I have the following code:
in = new BufferedReader(new FileReader("D/sample.txt"));
String str;
while ((str = in.readLine()) != null)
{
process(str);
}
Say sample.txt contains 'n' number of lines. I am passing the String object to another function process in the same class.The function process contains following code:
public void process(String s) {
String elements = s;
System.out.println(elements);
How can i print only the first line or the line that i wish to be printed. Please help.
If I understand you, you could pass in the lineCount - that is
in = new BufferedReader(new FileReader("D:/sample.txt")); // <-- added ':'
String str;
int lineCount = 0;
while ((str = in.readLine()) != null) {
process(str, lineCount++);
}
And then
public void process(String s, int lineCount) {
if (lineCount == 0) { // <-- only the first line.
System.out.println(s);
}
}
You can pass a flag to your process method to advise it to print or not. Something like this:
public void process(String s, boolean print) {
String elements = s;
if(print)
System.out.println(elements);
}
Just add a counter to your loop, and only call process on the lines you want to process.
in = new BufferedReader(new FileReader("D/sample.txt"));
String str;
int readLines = 0;
while ((str = in.readLine()) != null)
{
readLines++;
if(readLines == 1) //Only process first line
process(str);
}
Call process(str) only for the line you wish:
int lineToPrint = 1;
in = new BufferedReader(new FileReader("D/sample.txt"));
String str;
int i =1;
while ((str = in.readLine()) != null)
{
if (i==1){
process(str);
}
i++;
}

Categories

Resources