In: Computer Science
This week we really want to learn about a file I/O in Java.
In Java:
1) Create a plain empty text file named contacts.
2) Populate the text file with a person's name and account number on each line(Joe Doe 123456789). Create 10 accounts.
3) Store that file in the same location as your project
4) Write a program that will find that file and load it into the computers memory.
5) Read each line of the file and print the associated name but NOT the account number (remember the account number is 9 characters fixed)
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) throws FileNotFoundException { String fileName = "contacts.txt"; Random random = new Random(); PrintWriter printWriter = new PrintWriter(fileName); for (int i=1; i<=10; i++) { String name = "Name" + i; long accountNumber = (long) (random.nextDouble() * 1000000000); printWriter.write(name + " " + accountNumber + "\n"); } printWriter.close(); Scanner sc = new Scanner(new File(fileName)); System.out.println("The names stored in the file are: "); while (sc.hasNextLine()) { String line = sc.nextLine(); String name = line.split(" ")[0]; System.out.println(name); } } }
OUTPUT