Use Scanner to read int values from a file “input.txt” Read until end of file is
ID: 3805706 • Letter: U
Question
Use Scanner to read int values from a file “input.txt”
Read until end of file is reached
Write all program output to a file “output.txt”
Write all exceptions to a file “error.txt”
Output each number read
//What i have so far.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class lab5 {
public static void main(String[] args) throws FileNotFoundException {
String inputFile = "input.txt";
Scanner file = new Scanner(new File(inputFile));
String outputFile = "output.txt";
String errorFile = "error.txt";
PrintWriter er = new PrintWriter(errorFile);
int [] I = new int[1];
try{ I[10] = 2;}catch(Exception e){e.printStackTrace();
System.out.println(e.getMessage());}
er.close();
PrintWriter out = new PrintWriter(outputFile);
while(file.hasNext()){
out.println(file.next());
}
out.close();
}
}
Explanation / Answer
import java.awt.image.ImagingOpException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.util.Scanner;
public class Lab5 {
private static final String INPUTFILE = "C:\Users\cr\Desktop\input.txt";
private static final String OUTPUTFILE = "C:\Users\cr\Desktop\output.txt";
private static final String ERRORFILE = "C:\Users\cr\Desktop\error.txt";
public static void main(String[] args) throws FileNotFoundException {
String inputFile = INPUTFILE;
File inputfile = new File(inputFile);
String outputFile = OUTPUTFILE;
File outputfile=new File(outputFile);
File errorFile=new File(ERRORFILE);
BufferedWriter bw=null;
FileWriter fw=null;
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(inputfile);
br = new BufferedReader(fr);
fw=new FileWriter(outputfile);
bw=new BufferedWriter(fw);
String sCurrentLine;
br = new BufferedReader(new FileReader(inputfile));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println("reading file");
System.out.println(sCurrentLine);
System.out.println("writing startshere");
try {
bw = new BufferedWriter(fw);
bw.write(sCurrentLine);
bw.newLine();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
}
catch(IOException ie){
// fw=new FileWriter(errorFile);
// bw=new BufferedWriter(fw);
// bw.write(ie.getMessage());
// bw.newLine();
// ie.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.