Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The pledge of Allegiance states, “I pledge allegiance to the Flag of the United

ID: 3696889 • Letter: T

Question

The pledge of Allegiance states, “I pledge allegiance to the Flag of the United States of America, and to the Republic for which it stands: one Nation under God, indivisible, With Liberty and Justice for all.” Save the pledge, 174 characters, to a text file. Use the RandomAccessFile class to access the file. Using Seek method, display the characters at positions 124 and 135 only. Directions • Create a text file with the pledge of allegiance named Pledge.txt using notepad. • Create a reference to the file, Pledge.txt, using the RandomAccessFile class. • Use the Seek method to point at positions 124 and 135, then display the characters represented by the byte streams. • Use try, catch and finally blocks for exception handling.

Explanation / Answer

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomFileAccessTest {

   public static void main(String[] args) {
       String fileName = "D:/ravi/Cheg/pledge.txt";
       try {
           RandomAccessFile raf = new RandomAccessFile(new File(fileName),"r");
           System.out.println(raf.readLine());
              
               byte bytes[] = new byte[1];
               raf.seek(124);
               raf.read(bytes);
               System.out.println(" Char at :124 : "+new String(bytes));
              
               raf.seek(135);
               raf.read(bytes);
               System.out.println(" Char at :135 : "+new String(bytes));
              
       } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
          
       }
   }
  
}


---output-----------------

I pledge allegiance to the Flag of the United States of America, and to the Republic for which it stands: one Nation under God, indivisible, With Liberty and Justice for all.
Char at :124 : o
Char at :135 : i

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote