FileInputStream not reading first value - java

The file I need to read from looks like this:
30 15
6 3
12 20
3 4
(without the bullet points)
The inputStream isn't reading 30 and 15 but it's reading all the other ones.
How do I get the inputStream to read the first line?
import java.io.*;
import java.util.*;
public class Program6 {
// private static Fraction [] fractionArray;
public static void main(String[] args) throws FileNotFoundException, IOException {
System.out.println("Please enter the name of the input file: ");
Scanner inputFile = new Scanner(System.in);
Scanner outputFile = new Scanner(System.in);
String inputFileName = inputFile.nextLine();
System.out.println("Please enter the name of the output file: ");
String outputFileName = outputFile.nextLine();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
FileWriter fileWriter = new FileWriter(outputFileName, true);
//Declaring an inputstream to get file
Scanner inputStream = new Scanner(new FileInputStream(inputFileName));
//while the file still has a line
while (inputStream.hasNextLine()) {
String theLine = inputStream.nextLine();
if (theLine.length() >= 0) {
//declares a numerator and denominator from the file
int num = inputStream.nextInt();
int denom = inputStream.nextInt();
//new fraction from file
Fraction fract = new Fraction(num, denom);
fract.reduce();
System.out.println(fract);
fileWriter.write("" + fract + "\r\n");
}
}
//closes streams and flushes the file writer
fileWriter.flush();
fileWriter.close();
inputStream.close();
}
}

The issue here is Scanner.nextLine() consumes the line of input from the InputStream. Then, using Scanner.nextInt() goes back to consume from that same InputStream - it does not consume from the value returned by nextLine().
So, use one or the other.
If using the nextLine() approach, then the String containing the line will need to be parsed to extract the values. Using scanner.nextInt(), the integer value from the file is immediately available. The only loss is that then you lose knowledge of whether values were on the same line or different lines.

Related

Getting java.util.InputMismatchException

The program I'm trying to do:
"Use the file ("Eleven.txt") and delete the records with the marks in English and Science below 80 and marks under 90 in Computer Science"
I have tried adding 'sc.next()' and 'sc.nextLine()' between eng, sci, comp... But still no success.
The value in the "Eleven.txt" file is
a
A
10
20
30
b
B
20
30
40
c
C
40
50
60
d
D
60
70
80
e
E
70
8
90
"Science.txt" file is a blank file
import java.io.*;
import java.util.*;
public class filePg501Ex21{
public static void main() throws IOException{
String name1;
String name2;
int eng;
int sci;
int comp;
int ch;
int p = 0;
FileReader fr = new FileReader("Eleven.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("Science.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
Scanner sc = new Scanner(new File("Eleven.txt"));
while(sc.hasNext()){
name1 = sc.nextLine();
name2 = sc.nextLine();
eng = sc.nextInt();
sci = sc.nextInt();
comp = sc.nextInt();
if((eng >= 80) && (sci >= 80) && (comp >= 90)){
pw.println(name1);
pw.println(name2);
pw.println(eng);
pw.println(sci);
pw.println(comp);
}
}
fr.close();
br.close();
fw.close();
bw.close();
pw.close();
sc.close();
File f1 = new File("Eleven.txt");
f1.delete();
File f2 = new File("Science.txt");
boolean Rename = f2.renameTo(f1);
if(!Rename){
System.out.println("Renaming of the file not done");
}
else{
System.out.println("Renaming done sucesfully");
}
}
}
It looks to me like the error occurs in the second data set. The sc.nextInt() is not reading the carriage return after the final grade. So when the loop comes back for the second iteration, the first name1 field is blank, and the name2 field is b. That means when you read the eng value as an int, you get a value of B. That is the mismatch.
You should consider adding debug code to show you what the loop is doing to help you find this sort of problem.
There are almost certainly many ways to solve this.
Read another line after the last grade for instance.
Read the scores as lines and parse them to ints.

I need a program that will ask the user to enter the information to save, line to line in a file. How can I do it?

I need a program that will ask the user to enter the information to save, line to line in a file. How can I do it?
It has to look like this:
Please, choose an option:
1. Read a file
2. Write in a new file
2
File name? problema.txt
How many lines do you want to write? 2
Write line 1: Hey
Write line 2: How are you?
Done! The file problema.txt has been created and updated with the content given.
I have tried in various ways but I have not succeeded. First I have done it in a two-dimensional array but I can not jump to the next line.
Then I tried it with the ".newline" method without the array but it does not let me save more than one word.
Attempt 1
System.out.println("How many lines do you want to write? ");
int mida = sc.nextInt();
PrintStream escriptor = new PrintStream(f);
String [][] dades = new String [mida][3];
for (int i = 0; i < dades.length; i++) {
System.out.println("Write line " + i + " :");
for (int y=0; y < dades[i].length; y++) {
String paraula = sc.next();
System.out.println(paraula + " " + y);
dades[i][y] = paraula;
escriptor.print(" " + dades[i][y]);
}
escriptor.println();
}
Attempt 2
System.out.println("How many lines do you want to write? ");
int mida = sc.nextInt();
PrintStream escriptor = new PrintStream(f);
BufferedWriter ficheroSalida = new BufferedWriter(new FileWriter(new File(file1)));
for (int i = 0; i < mida; i++) {
System.out.println("Write line " + i + " :");
String paraula = sc.next();
ficheroSalida.write (paraula);
ficheroSalida.newLine();
ficheroSalida.flush();
}
System.out.println("Done! The file " + fitxer + " has been created and updated with the content given. ");
escriptor.close();
Attempt 1:
Write line 1: Hey How are
Write line 1: you...
Attempt 2:
Write line 1: Hey
Write line 2: How
Write line 3: are
Write line 4: you
Write line 5: ?
Well, you're almost there. First, I'd use a java.io.FileWriter in order to write the strings to a file.
It's not really necessary to use an array here if you just want to write the lines to a file.
You should also use the try-with-resources statement in order to create your writer. This makes sure that escriptor.close() gets called even if there is an error. You don't need to call .flush() in this case either because this will be done before the handles gets closed. It was good that you intended to do this on your own but in general its safer to use this special kind of statement whenever possible.
import java.io.*;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
File f = new File("/tmp/output.txt");
System.out.println("How many lines do you want to write? ");
int mida = sc.nextInt();
sc.nextLine(); // Consume next empty line
try (FileWriter escriptor = new FileWriter(f)) {
for (int i = 0; i < mida; i++) {
System.out.println(String.format("Write line %d:", i + 1));
String paraula = sc.nextLine();
escriptor.write(String.format("%s\n", paraula));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In cases where your text file is kind of small and usage of streamreaders/streamwriters is not required, you can read the text, add what you want and write it all over again. Check this example:
public class ReadWrite {
private static Scanner scanner;
public static void main(String[] args) throws FileNotFoundException, IOException {
scanner = new Scanner(System.in);
File desktop = new File(System.getProperty("user.home"), "Desktop");
System.out.println("Yo, which file would you like to edit from " + desktop.getAbsolutePath() + "?");
String fileName = scanner.next();
File textFile = new File(desktop, fileName);
if (!textFile.exists()) {
System.err.println("File " + textFile.getAbsolutePath() + " does not exist.");
System.exit(0);
}
String fileContent = readFileContent(textFile);
System.out.println("How many lines would you like to add?");
int lineNumber = scanner.nextInt();
for (int i = 1; i <= lineNumber; i++) {
System.out.println("Write line number #" + i + ":");
String line = scanner.next();
fileContent += line;
fileContent += System.lineSeparator();
}
//Write all the content again
try (PrintWriter out = new PrintWriter(textFile)) {
out.write(fileContent);
out.flush();
}
scanner.close();
}
private static String readFileContent(File f) throws FileNotFoundException, IOException {
try (BufferedReader br = new BufferedReader(new FileReader(f))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
return everything;
}
}
}
An execution of the example would be:
Yo, which file would you like to edit from C:\Users\George\Desktop?
hello.txt
How many lines would you like to add?
4
Write line number #1:
Hello
Write line number #2:
Stack
Write line number #3:
Over
Write line number #4:
Flow
with the file containing after:
Hello
Stack
Over
Flow
And if you run again, with the following input:
Yo, which file would you like to edit from C:\Users\George\Desktop?
hello.txt
How many lines would you like to add?
2
Write line number #1:
Hey
Write line number #2:
too
text file will contain:
Hello
Stack
Over
Flow
Hey
too
However, if you try to do it with huge files, your memory will not be enough, hence an OutOfMemoryError will be thrown. But for small files, it is ok.

How to incorporate a method in a filewriter

I'm having trouble with one of my homework problems, I think i've done everything right up until the last part which is to call the method and write the method to the output file. Here is the assignment:
Write a method isPrime which takes a number and determines whether the
number is prime or not. It returns a Boolean.
Write a main method that asks the user for an input file that contains
numbers and an output file name where it will write the prime numbers
to.
Main opens the input file and calls isPrime on each number. Main
writes the prime numbers to the output file.
Modify main to throw the appropriate exceptions for working with
files.
I've tried several different ways to write the method with the output file but I'm not sure exactly how to do it.
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the input file?");
String inputfile = keyboard.nextLine();
File f = new File(inputfile);
System.out.println("What is the name of the output file?");
String outputfile = keyboard.nextLine();
Scanner inputFile = new Scanner(f);
FileWriter fw = new FileWriter(outputfile);
PrintWriter pw = new PrintWriter(new File(outputfile));
while (inputFile.hasNextLine()) {
pw.write(inputFile.nextLine().isPrime());
pw.write(System.lineSeparator());
}
pw.close();
inputFile.close();
}
public static void isPrime (int num) throws IOException {
boolean flag = false;
for (int i =2; i <= num/2; i++) {
if (num % i ==0) {
flag = true;
break;
}
}
if (!flag)
System.out.println(num + "is a prime number");
else
System.out.println(num + "is not a prime number");
}
I need the program to be able to read a inputfile of a different numbers and then write out to the output file which of those numbers is prime.
You wrote "inputFile.nextLine().isPrime()". But inputFile.nextLine() gives you back a String. There is no method isPrime() that you can call on a String, therefore you will get a compilation error.
You must first convert it to an integer, pass it to your method, and then deal with the result:
isPrime(Integer.parseInt(inputFile.nextLine()));
I suggest you just return a message string from your method isPrime() instead of void, then you can deal with it properly:
pw.write(isPrime(Integer.parseInt(inputFile.nextLine())));
ADDENDUM:
I modified your code so you can see where to add the suggested lines. I also left out unnecessary lines.
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the input file?");
String inputfile = keyboard.nextLine();
File f = new File(inputfile);
System.out.println("What is the name of the output file?");
String outputfile = keyboard.nextLine();
Scanner inputFile = new Scanner(f);
PrintWriter pw = new PrintWriter(new File(outputfile));
while (inputFile.hasNextLine()) {
String nextLine = inputFile.nextLine();
boolean isPrime = isPrime(Integer.parseInt(nextLine));
if (isPrime) {
pw.write(nextLine + System.lineSeparator());
}
}
pw.close();
inputFile.close();
}
public boolean isPrime (int num) {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
TODO: put your file-opening code inside a try-catch-finally block and put your close() commands into its finally block. (If you don't know why it should be inside finally, just ask)

How to read reads a file containing text. Read each line and send it to the output file, preceded by line numbers

this program does not create the files
Scanner in = new Scanner(System.in);
System.out.print("Input file: ");
String Mary = in.next();
System.out.print("Output file: ");
String outMary = in.next();
File inFile = new File ("Mary.txt");
Scanner inputFile = new Scanner(inFile);
PrintWriter outFile = new PrintWriter("Mary2.txt");
while (inputFile.hasNext())
{
String input = in.nextLine();
outFile.println(input);
}
I want to read a file I created and copy its contents into another with line numbers before each line.
try this code, this will create new file for output. Note, this will erase file, if it existed before writing
File inFile = new File("Mary.txt");
Scanner inputFile = new Scanner(inFile);
try(BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Mary2.txt")))) {
int i=0;
while (inputFile.hasNext()) {
String input = inputFile.next();
bw.write(i+"\\ ");
i++;
}
bw.flush();
}

java multiple random integer saving to txt file

How would I save the secretNumber to a text file multiple times? As opposed to just that last time that I ran the program. Thanks to all who have helped.
import java.io.PrintStream;
public class Recursion {
public Recursion() {}
public static void main(String[] args) {
int secretNumber = (int)(Math.random() * 99.0D + 1.0D);
java.util.Scanner keyboard = new java.util.Scanner(System.in);
int input;
do {
System.out.print("Guess what number I am thinking of (1-100): ");
input = keyboard.nextInt();
if (input == secretNumber) {
System.out.println("Your guess is correct. Congratulations!");
} else if (input < secretNumber)
{
System.out.println("Your guess is smaller than the secret number.");
} else if (input > secretNumber)
{
System.out.println("Your guess is greater than the secret number."); }
} while (input != secretNumber);
File output = new File("secretNumbers.txt");
FileWriter fw = null; //nullifies fw
try {//Text File Creating
fw = new FileWriter(output);
BufferedWriter writer = new BufferedWriter(fw);
//FOURTH COMPETENCY: fundamentals of Characters and Strings
writer.write(String.valueOf(saveNum));
writer.newLine();//adds a new line to the .txt file
System.out.println("The secret number has been saved");
writer.close();
}
}
Use new FileWriter(output, true);. The second argument true specifies that, instead of overwriting the entire file, you keep the old contents of the file and append the new content to the end of the file instead.
Currently your code will cause the file to be overwritten each time it is run. In order to continue adding numbers to the file on each run instead, you need to append to the file.
To do this, all you have to do is enable append mode for the FileWriter when you create it. You can do this by passing true as the second argument to the constructor like so:
fw = new FileWriter(output, true);

Categories