Write a Java method readFile() that reads values from a file and prints the valu
ID: 3847464 • Letter: W
Question
Write a Java method readFile() that reads values from a file and prints the values each in its own line on the console. In coderunner the file is hidden from you and is instead made available to you via an InputStream object referenced by the istream instance variable in the class in which your method will be placed. The file contains two char values and a boolean value, in that order Use the istream object instead of Files.newInputStream(Paths.get("ellipsis") to read from the file. For example:Explanation / Answer
/* package codechef; // don't place package name! */
import java.util.*;
import java.io.File;
import java.io.IOException;
public class ReadTextFile
{
public static void main(String[] args)
throws IOException
{
Scanner textfile = new Scanner(new File("file.txt"));// the address of the file you are supposed to read. make sure you give full address in case its not in the direct directory, i.e c/programs/java..(this is only for sample)
readFile(textfile);
}
static void readFile (Scanner textfile)
{
int c;//to store the read data
char ch;//store character correspondent of int data
try{
while ((c = textfile.read()) != -1){//reading the file data in integer form unless the end of file is reached, denoted by -1
ch=(char)c;//converting int data to char
System.out.print(ch);//priting the values to the console
}
textfile.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Do thumbs up! ^ ^
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.