Exercise 1 Description Your code will prompt the user to enter a file name. If t
ID: 653213 • Letter: E
Question
Exercise 1 Description
Your code will prompt the user to enter a file name. If this file does not exist the program will produce an error message and exit. Otherwise the program will open the file and read a line from the file, reverse the line, and then print the line to the console. The program should process the entire file and terminate properly when the end of the file is reached.
Exercise 1 Sample Output
This is a sample transcript of what your program should do, assuming that the file lab13aInput.txt file provided above is used. Text in bold is expected input from the user rather than output from the program.
Enter an input name: lab13aInput.txt
ykcowrebbaJ
sevot yhtils eht dna ,gillirb sawT'
;ebaw eht ni elbmig dna eryg diD
,sevogorob eht erew ysmim llA
.ebargtuo shtar emom eht dnA
!nos ym ,kcowrebbaJ eht eraweB"
!hctac taht swalc eht ,etib taht swaj ehT
nuhs dna ,drib bujbuJ eht eraweB
"!hctansrednaB suoimurf ehT
:dnah ni drows laprov sih koot eH
Explanation / Answer
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; /** * * @author Kevin */ public class ReverseLineInputStream extends InputStream { RandomAccessFile in; long currentLineStart = -1; long currentLineEnd = -1; long currentPos = -1; long lastPosInFile = -1; public ReverseLineInputStream(File file) throws FileNotFoundException { in = new RandomAccessFile(file, "r"); currentLineStart = file.length(); currentLineEnd = file.length(); lastPosInFile = file.length() -1; currentPos = currentLineEnd; } public void findPrevLine() throws IOException { currentLineEnd = currentLineStart; // There are no more lines, since we are at the beginning of the file and no lines. if (currentLineEnd == 0) { currentLineEnd = -1; currentLineStart = -1; currentPos = -1; return; } long filePointer = currentLineStart -1; while ( true) { filePointer--; // we are at start of file so this is the first line in the file. if (filePointer < 0) { break; } in.seek(filePointer); int readByte = in.readByte(); // We ignore last LF in file. search back to find the previous LF. if (readByte == 0xA && filePointer != lastPosInFile ) { break; } } // we want to start at pointer +1 so we are after the LF we found or at 0 the start of the file. currentLineStart = filePointer + 1; currentPos = currentLineStart; } public int read() throws IOException { if (currentPosRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.