How to Print Object Line by line - java

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

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.

readLine() null return

I have the following code:
public static void main(String[] args) throws Exception {
String s = "";
StringBuilder sb = new StringBuilder();
File file = new File("C:\\New\\r.txt");
BufferedReader in = new BufferedReader(new FileReader(file));
while(in.readLine() != null) {
sb.append(in.readLine());
}
System.out.println(sb);
s = sb.toString();
byte[] b = s.getBytes();
for(int i = 0; i < b.length; i++) {
if(b[i] == 1){ b[i]=0; }
if(b[i] == 0){ b[i]=1; }
}
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fos);
dos.write(b);
in.close();
fos.close();
dos.close();
}
I get a return of null when I run this program. Maybe I must elevate the program? Help would be appreciated.
Change:
while(in.readLine()!=null)
to:
while((s = in.readLine())!=null)
and then:
sb.append(s);
When you call in your code to in.readLine() twice - you're reading two lines but printing only the second in each iteration.
You're throwing away every odd line:
while(in.readLine()!=null)
{
sb.append(in.readLine());
}
If r.txt only contains one line, you will get the string "null" in the StringBuffer, because the first line of StringBuffer.append does this:
public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
....
}
If there are two lines, you will get the first line with "null" at the end of the line.
The following will append all lines from the file to the StringBuffer:
String line = null;
while((line = in.readLine()) != null)
{
sb.append(line);
}
your code
while(in.readLine() != null) {
sb.append(in.readLine());
}
change with it
while ((s = in.readLine()) != null)
{
sb.append(s);
}

How can I count these values?

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.

Read file and insert data into String[]

public static String[] words = null;
public static String readFile(String name) {
int i = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(name));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
i++;
sb.append(sb.toString());
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
words = everything.split("\\n");//not sure if this is right...
} finally {
br.close();
}
} catch (Exception e) {
e.getMessage();
}
return "Loaded " + i + " words";
}
I'm basically trying to read a file with data on each line. On each line in the file I'm trying to insert into the array. May someone help me figure out what I'm doing wrong here?
The problem is that:
while (line != null) {
i++;
sb.append(sb.toString());
sb.append("\n");
line = br.readLine();
}
sb is never actually appended anything, it is just appending empty strings over and over again.
should be:
while (line != null) {
i++;
sb.append(line);
sb.append("\n");
line = br.readLine();
}

Categories

Resources