I am working on a homework assignment for Principles of Programming 1 and I am struggling to figure it out.
The assignment states:
Write a program to create a new file (e.g. named scaled.txt) if it does not exist (If the file exists, terminate your program without doing anything.). Multiply all the numbers from an existing file with integer numbers (e.g. original.txt) by 10 and save all the new numbers in the new file (e.g. scaled.txt).
For example, if the existing file (original.txt) is:
26
12
4
89
54
65
12
65
74
3
Then the new file (scaled.txt) should be:
260
120
40
890
540
650
120
650
740
30
This is what I've written so far:
//Bronson Lane 11/28/15
//This program reads a file, multiplies the data in the file by 10, then exports that new data
//to a new file
package hw12;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class HW12Part2 {
public static void main(String[] args) throws Exception{
File file1 = new File("/Users/bronsonlane/Documents/workspace/hw12/original.rtf");
if (!file1.exists()) {
System.out.println("File does not exist");
System.exit(0);
}
int newNum = 0;
Scanner input = new Scanner(file1);
while (input.hasNextInt()) {
int num = input.nextInt();
newNum = num * 10;
}
PrintWriter output;
File file2 = new File("/Users/bronsonlane/Documents/workspace/hw12/scaled.rtf");
if (file2.exists()) {
System.exit(0);
}
output = new PrintWriter(file2);
while (input.hasNextInt()) {
int num = input.nextInt();
newNum = num * 10;
output.println(newNum);
}
output.close();
}
}
My issue now is that the console is outputting:
File does not exist
regardless of the file being there.
I figured that would be the best way to get it to print to the new file, but apparently it isn't since it doesn't work at all.
I know I am missing some key elements to complete the program, but I just can't figure them out.
*Edit 1: Updated code and a new issue *Edit 2: Doh! I stupidly put the wrong file path. All is well and the program runs as expected.
You can open a file in reading and while reading the file line y line you can directly output the updated line into the new file. See below a code example that opens a file wit integers and update the integers and then add them to another file:
public static void main(String[] args) throws FileNotFoundException {
//open file containing integers
File file = new File("C:\\test_java\\readnumbers.txt");
//instruct Scanner to read from file source
Scanner scanner = new Scanner(file);
//create file object for output
File outFile = new File("C:\\test_java\\incremented_numbers.txt");
//print writer with source as file
PrintWriter writer = new PrintWriter(outFile);
//for each line in input file
while(scanner.hasNext()) {
//get the integer in the line
int number = scanner.nextInt();
number *= 10;
//write the updated integer in the output file
writer.println(number);
}
//close both streams
scanner.close();
writer.close();
}