Search for multiline String in a text file

I have a text file from which i am trying to search for a String which has multiple lines. A single string i am able to search but i need multi line string to be searched.

I have tried to search for single line which is working fine.

public static void main(String[] args) throws IOException 
{
  File f1=new File("D:\\Test\\test.txt"); 
  String[] words=null;  
  FileReader fr = new FileReader(f1);  
  BufferedReader br = new BufferedReader(fr); 
  String s;     
  String input="line one"; 

  // here i want to search for multilines as single string like 
  //   String input ="line one"+
  //                 "line two";

  int count=0;   
  while((s=br.readLine())!=null)   
  {
    words=s.split("\n");  
    for (String word : words) 
    {
      if (word.equals(input))   
      {
        count++;    
      }
    }
  }

  if(count!=0) 
  {
    System.out.println("The given String "+input+ " is present for "+count+ " times ");
  }
  else
  {
    System.out.println("The given word is not present in the file");
  }
  fr.close();
}

And below are the file contents.

line one  
line two  
line three  
line four

Solution:

Use the StringBuilder for that, read every line from file and append them to StringBuilder with lineSeparator

StringBuilder lineInFile = new StringBuilder();

while((s=br.readLine()) != null){
  lineInFile.append(s).append(System.lineSeparator());
}

Now check the searchString in lineInFile by using contains

StringBuilder searchString = new StringBuilder();

builder1.append("line one");
builder1.append(System.lineSeparator());
builder1.append("line two");

System.out.println(lineInFile.toString().contains(searchString));

JAVA- Read integers from txt file and compute integers

I need some help with the code below.
What I’m trying to do is to write a program that reads in the file and computes the average grade and prints it out. I’ve tried several methods, like parsing the text file into parallel arrays, but I run into the problem of having the % character at the end of the grades. The program below is meant to add integers up too but the output is “No numbers found.”

This is a clip of the text file (the whole file is 14 lines of similar input):

Arthur Albert,74% 
Melissa Hay,72%
William Jones,85%
Rachel Lee,68%
Joshua Planner,75%
Jennifer Ranger,76%

This is what I have so far:

final static String filename = "filesrc.txt";

public static void main(String[] args) throws IOException {

          Scanner scan = null;
          File f = new File(filename);
          try {
             scan = new Scanner(f);
          } catch (FileNotFoundException e) {
             System.out.println("File not found.");
             System.exit(0);
          }

          int total = 0;
          boolean foundInts = false; //flag to see if there are any integers

          while (scan.hasNextLine()) { //Note change
             String currentLine = scan.nextLine();
             //split into words
             String words[] = currentLine.split(" ");

             //For each word in the line
             for(String str : words) {
                try {
                   int num = Integer.parseInt(str);
                   total += num;
                   foundInts = true;
                   System.out.println("Found: " + num);
                }catch(NumberFormatException nfe) { }; //word is not an integer, do nothing
             }
          } //end while 

          if(!foundInts)
             System.out.println("No numbers found.");
          else
             System.out.println("Total: " + total);

          // close the scanner
          scan.close();
       }            
}

Any help would be much appreciated!

Solution:

Here’s the fixed code. Instead of splitting the input using

" "

you should have split it using

","

That way when you parse the split strings you can use the substring method and parse the number portion of the input.

For example, given the string

Arthur Albert,74%

my code will split it into Arthur ALbert and 74%.
Then I can use the substring method and parse the first two characters of 74%, which will give me 74.

I wrote the code in a way so that it can handle any number between 0 and 999, and added comments when I made additions that you didn’t already have. If you still have any questions however, don’t be afraid to ask.

final static String filename = "filesrc.txt";

public static void main(String[] args) throws IOException {

          Scanner scan = null;
          File f = new File(filename);
          try {
             scan = new Scanner(f);
          } catch (FileNotFoundException e) {
             System.out.println("File not found.");
             System.exit(0);
          }

          int total = 0;
          boolean foundInts = false; //flag to see if there are any integers
             int successful = 0; // I did this to keep track of the number of times
             //a grade is found so I can divide the sum by the number to get the average

          while (scan.hasNextLine()) { //Note change
             String currentLine = scan.nextLine();
             //split into words
             String words[] = currentLine.split(",");

             //For each word in the line
             for(String str : words) {
                 System.out.println(str);
                try {
                    int num = 0;
                    //Checks if a grade is between 0 and 9, inclusive
                    if(str.charAt(1) == '%') {
                        num = Integer.parseInt(str.substring(0,1));
                        successful++;
                        total += num;
                       foundInts = true;
                       System.out.println("Found: " + num);
                    }
                    //Checks if a grade is between 10 and 99, inclusive
                    else if(str.charAt(2) == '%') {
                        num = Integer.parseInt(str.substring(0,2));
                        successful++;
                        total += num;
                       foundInts = true;
                       System.out.println("Found: " + num);
                    }
                    //Checks if a grade is 100 or above, inclusive(obviously not above 999)
                    else if(str.charAt(3) == '%') {
                        num = Integer.parseInt(str.substring(0,3));
                        successful++;
                        total += num;
                       foundInts = true;
                       System.out.println("Found: " + num);
                    }
                }catch(NumberFormatException nfe) { }; //word is not an integer, do nothing
             }
          } //end while 

          if(!foundInts)
             System.out.println("No numbers found.");
          else
             System.out.println("Total: " + total/successful);

          // close the scanner
          scan.close();
       }

How to read these data from a file in JAVA

I have this format of data

n
l
p1(x1) p1(x2) imp(p1)
p2(x1) p2(x2) imp(p2)
: : :
pl(x1) pl(x2) imp(pl)
r
q1(x1) q1(x2) imp(q1)
q2(x1) q2(x2) imp(q2)
: : :
qr(x1) qr(x2) imp(qr)

where n, l(number of p’s) , and r(number of q’s) are integers. I know how to read only integers from a file but how I can read the lines that includes strings and get the values of x1, x2, and p1 for each line?! Thanks in Advance.

Here is my code for reading integers only.

try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;
            while ((text = reader.readLine()) != null) {
                // The first line gives the number of nodes (You will use to create the int[][] graph = new int[nOfNodes][nOfNodes];)
                if (c == 0) {
                    numberOfNodes = Integer.parseInt(text.trim());
                } // The second one gives the number of edges
                else if (c == 1) {
                    nOfEdges = Integer.parseInt(text.trim());
                    graph2 = new double[nOfEdges][3];
                } // And third the list of special nodes
                // `nodes` will now contains only your special constrained one
                else if (c == 2) {
                    String[] str = text.split(" ");
                    for (int i = 0; i < str.length; i++) {
                        if (str[i].trim().length() > 0) {
                            nodes.add(Integer.parseInt(str[i]));
                        }
                    }
                } else { // Then you have your edges descriptors
                    String[] str = text.split(" ");
                    for (int i = 0; i < str.length; i++) {
                        if (str[i].trim().length() > 0) {
                            graph2[c - 4][i] = Double.parseDouble(str[i]);
                        }
                    }
                }
                c++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                System.out.print(e);
            }
        }

Solution:

Using matcher class like this

public static int numberOfPoints = -1, p=-1, q=-1;

    public static void main(String[] args) throws FileNotFoundException {

        ArrayList<Integer> dots = new ArrayList<>();
        int c = 0;
        File file = new File("D:\\ALGORTHIMS\\MASTER LEVEL\\dr. khaled\\assignment 3\\a.txt");
        BufferedReader reader = null;


        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;
            while ((text = reader.readLine()) != null) {

                try {
                    if(c==0)
                    { numberOfPoints=Integer.parseInt(text); c=1;}
                    if(c==1)
                    { p=Integer.parseInt(text);c=2;}
                    if(c==2)
                        q=Integer.parseInt(text);

                } catch (NumberFormatException e) {

                    Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(text);
        while (m.find()) {

           dots.add(Integer.parseInt(m.group(1)));
        }

                }

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                System.out.print(e);
            }
        }