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

Java I/O question Write a Java method readFile() that reads values from a file a

ID: 3847252 • Letter: J

Question

Java I/O 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 integer values and a double value, in that order. Use the istream object instead of Files.newInputstream (Paths.get("...")); to read from the file.

Explanation / Answer

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

public class ReadData{
public static void main(String args[]) throws IOException{
writeFile(34,67,12.324);// function to write data to the file
readFile();// function to read data to the file
}

private static void writeFile(int num1, int num2, double num3) throws IOException {//definition of writeFile function
PrintWriter pw=new PrintWriter(new FileWriter("C:\Users\SuNiL\Desktop\Values.txt"));//specifying the loaction of the file
pw.println(num1);//writing the first number
pw.println(num2);//writing the second number
pw.println(num3);//writing third number
pw.flush();//moving values from writer to file
}

private static void readFile() throws FileNotFoundException, IOException {//definition of read function
InputStream istream=new FileInputStream("C:\Users\SuNiL\Desktop\Values.txt");//location of file to be read
int c;//to store the read data
char ch;//store character correspondent of int data
while ((c = istream.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
}
}
}

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