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

In this lab, you will be asking the user for the name of an input file and the n

ID: 3821544 • Letter: I

Question

In this lab, you will be asking the user for the name of an input file and the name of an output file. You will read the input file, modify each line, and write each modified line to the output file. Each line of the input file should be in the form ::. For each line, you should take the substring of str between indices i and j. If any line is malformed (is not of this form, or would cause an illegal substring), you should write a blank line in the file instead.

Input File:

examplestring:0:5

examplestring:1:6

examplestring:2:7

examplestring:x

examplestring:7:2

Output File:

examp

xampl

ample

Explanation / Answer

ReadFileSubStringTest.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;


public class ReadFileSubStringTest {

  
   public static void main(String[] args) throws FileNotFoundException {
       Scanner scnr = new Scanner(System.in);
       System.out.println("Enter the input file name: ");
       String inputFileName = scnr.next();
       System.out.println("Enter the output file name: ");
       String outputFileName = scnr.next();
      
       File input = new File(inputFileName);
       File output = new File(outputFileName);
       PrintWriter pw = new PrintWriter(output);
       Scanner scan = new Scanner(input);
       while(scan.hasNextLine()){
           try{
           String line = scan.nextLine();
           String values[] = line.split(":");
           String s = values[0];
          
           int firstIndex = Integer.parseInt(values[1]);
           int lasstIndex = Integer.parseInt(values[2]);
           if(firstIndex <= lasstIndex){
               s = s.substring(firstIndex,lasstIndex);
               System.out.println(s);
               pw.write(s+" ");
           }
           else{
               System.out.println(" ");
               pw.write(" ");
           }
           }
           catch(Exception e){
               System.out.println(" ");
               pw.write(" ");
           }
       }
       pw.flush();
       pw.close();
       scan.close();
      
   }

}

Output:

Enter the input file name:
D:\inputfile.txt
Enter the output file name:
D:\outputfile.txt
examp
xampl
ample

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