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)
Java Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws
FileNotFoundException {
//creating a scanner
Scanner sc = new Scanner(new
File("contacts.txt"));
//while there is lines in the
file
while(sc.hasNext()) {
//get the
line
String line =
sc.nextLine();
//print the part
of the line that has the name
System.out.println(line.substring(0, line.length()-9));
}
}
}
Sample Output:
Joe Doe
Test1
Test2
Test3
Test4 LastName
Test5
Test6
Test7
Test8
Test9
contacts.txt
Joe Doe 123456789
Test1 546738219
Test2 673821123
Test3 821123456
Test4 LastName 123456175
Test5 456175895
Test6 175895164
Test7 895164841
Test8 164841724
Test9 841724473