JAVA programming through eclipse. This is an introduction class so the code is f
ID: 3597105 • Letter: J
Question
JAVA programming through eclipse. This is an introduction class so the code is fairly simple.
#1. Read names from an input file called “names.txt” and write those names to an output file called “names2.txt”. (Use "example" names in code)
The input file should have two strings on each line separated by a space, which are the first then the last name. The output file should have last, first. No need to sort them into alphabetical order. Example:
If the input file contains:
Mary Jones
Juan Garcia
Chris Young
The output file should then contain:
Jones, Mary
Garcia, Juan
Young, Chris
Explanation / Answer
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
/**
*
* @author Namburi Ramesh
*/
public class FileIO {
public static void main(String[] args) throws FileNotFoundException, IOException{
Scanner inFile = new Scanner(new File("names.txt")); // initialise a input file stream
FileWriter outFile = new FileWriter(new File("names2.txt")); //initialise a output file stream
String first,last;
//read from the input file and write to the output file
while(inFile.hasNext()){
first = inFile.next();
last = inFile.next();
outFile.append(last+","+first+" ");
}
outFile.close();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.