Techknow Study

Reading a file through Bean Shell

2:08:00 PM vikas 0 Comments Category :

Reading a file through Bean Shell in Jmeter

    We can read a file in JMeter using different Classes and These are below.
           1.FileReader class
           2.FileInputStream class
    Now if we try to dig little deep about these classes,First we need to know when to use "InputStream" and when to go for "Reader". Main difference between them is, InputStream is used to read binary data, while Reader is used to read text data.

    An InputStream is the method of getting information from resource. It observe the data byte by byte without performing any kind of translation. If you are reading image data, or any binary file, this method is used.

    A Reader is used for character streams. If the information you are reading is all text, then the Reader will take care of the character decoding for you and give you unicode characters from the raw input stream. If you are reading any type of text, this method is used.

    Now other thing is we can read the file in two ways,
                1. char by char.
                2. line by line.


    1. File Reader - 
    Read Char by char:
    import java.io.FileReader;
    FileReader fileReader=new FileReader("Path/Example.txt");
    int i =fileReader.read();
    while(i!=-1)
    {
      System.out.print((char)i);
      i=fileReader.read();
    }
    2. File Reader - Read line by line:
    import java.io.FileReader;
    FileReader fileReader=new FileReader("
    Path/Example.txt");
    BufferedReader bufferReader= new BufferedReader(fileReader);
    String line=bufferReader.readLine();
    while(line!=null)
    {
        System.out.println(line);
        line=bufferReader.readLine();
    }
       fileReader.close();
       bufferReader.close();

    3. File Input Stream- Read Char by char :
    import java.io.FileInputStream;System.out.println("Method");
    FileInputStream fileInputStream=new FileInputStream("Path/Example.txt");
    int i=fileInputStream.read();
    while (i!=-1)
    {
    System.out.print((char)i);
    i=fileInputStream.read();
    }
    fileInputStream.close();
    4. File Input Stream -Read line by line:
    import java.io.FileInputStream;
    FileInputStream 
    fileInputStream= new FileInputStream("Path/Example.txt");
    InputStreamReader i
    nputStreamReader=new InputStreamReader(fileInputStream);//An InputStreamReader is a bridge from byte streams to character streams
    BufferedReader br = new BufferedReader(
    inputStreamReader);
    String line=br.readLine();
    while(line!= null)
    {
      System.out.println(line);
          line=br.readLine();
    }
      
    inputStreamReader.close(); 
      
    fileInputStream.close();

    Notes:-
    1.path:- It is the location where your resource file is present.

    RELATED POSTS

    0 comments