Reading and writing to a file
For this assignment just read a file and write to that same file and add the number 1 to each word, not numerically string wise. Punctuation doesn't matter. It works sort of, however when I run it to a text file it just makes the txt file blank. Any ideas? Thanks, oh and I can't change echo at all! I have 3 classes, writerDriver(main), echo, and writer. They are in order respectively.
Code:
import java.util.Scanner;
import java.io.*;
public class WriterDriver {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String fileName;
Scanner nameReader = new Scanner(System.in);
System.out.println("Enter a file name");
fileName = nameReader.nextLine();
Scanner scan = new Scanner(new FileReader(fileName));
Writer d = new Writer(fileName);
d.readLines();
scan.close();
}
}
Code:
import java.util.Scanner;
import java.io.*;
public class Echo{
String fileName; // external file name
Scanner scan; // Scanner object for reading from external file
public Echo(String f) throws IOException
{
fileName = f;
scan = new Scanner(new FileReader(fileName));
}
public void readLines(){ // reads lines, hands each to processLine
while(scan.hasNext()){
processLine(scan.nextLine());
}
scan.close();
}
public void processLine(String line){ // does the real processing work
System.out.println(line);
}
}
Code:
import java.util.Scanner;
import java.io.*;
import java.util.StringTokenizer;
public class Writer extends Echo {
PrintWriter writer = new PrintWriter(fileName);
public Writer(String f) throws IOException {
super(f);
}
public void readLines(){ // reads lines, hands each to processLine
super.readLines();
scan.close();
}
public void processLine(String line){ // does the real processing work
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
writer.print(st.nextToken+"1");
writer.println("");
}
writer.close();
}
}