I am trying to do a file I/O in eclipse. Here is the code:
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class TextDB {
public static final String SEPARATOR = "|";
// an example of reading
public static ArrayList readProfessors(String filename) throws IOException {
// read String from text file
ArrayList stringArray = (ArrayList) read(filename);
ArrayList alr = new ArrayList();// to store Professors data
for (int i = 0; i < stringArray.size(); i++) {
String st = (String) stringArray.get(i);
// get individual 'fields' of the string separated by SEPARATOR
StringTokenizer star = new StringTokenizer(st, SEPARATOR); // pass in the string to the string tokenizer using delimiter ","
String name = star.nextToken().trim(); // first token
String email = star.nextToken().trim(); // second token
int contact = Integer.parseInt(star.nextToken().trim()); // third token
// create Professor object from file data
Professor prof = new Professor(name, email, contact);
// add to Professors list
alr.add(prof);
}
return alr;
}
// an example of saving
public static void saveProfessors(String filename, List al) throws IOException {
List alw = new ArrayList();// to store Professors data
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
StringBuilder st = new StringBuilder();
st.append(prof.getName().trim());
st.append(SEPARATOR);
st.append(prof.getEmail().trim());
st.append(SEPARATOR);
st.append(prof.getContact());
alw.add(st.toString());
}
write(filename, alw);
}
/**
* Write fixed content to the given file.
*/
public static void write(String fileName, List data) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter(fileName));
try {
for (int i = 0; i < data.size(); i++) {
out.println((String) data.get(i));
}
} finally {
out.close();
}
}
/**
* Read the contents of the given file.
*/
public static List read(String fileName) throws IOException {
List data = new ArrayList();
Scanner scanner = new Scanner(new FileInputStream(fileName));
try {
while (scanner.hasNextLine()) {
data.add(scanner.nextLine());
}
} finally {
scanner.close();
}
return data;
}
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
}
And my Professor class:
import java.io.Serializable;
public class Professor implements Serializable {
private String name;
private String email;
private int contact;
public Professor(String n, String e, int c) {
name = n;
email = e;
contact = c;
}
public String getName() {
return name;
}
public int getContact() {
return contact;
}
public String getEmail() {
return email;
}
public boolean equals(Object o) {
if (o instanceof Professor) {
Professor p = (Professor) o;
return (getName().equals(p.getName()));
}
return false;
}
}
However, when I run it, the compiler told the the specified file "professor.txt" is not found. I thought the compiler will create the text file automatically based on these code?
Thanks in advance.
Before attempting to read the file in your application, create it if it doesn't exist, either directly :
String filename = "professor.txt" ;
File file = new File(fileName);
if(!file.exists()){
file.createNewFile();
}
Or by calling your write method.
String filename = "professor.txt" ;
File file = new File(fileName);
if(!file.exists()){
TextDB.saveProfessors(filename, new ArrayList());
}
The PrintWriter will create the file for you, even though nothing is written to it (like with this empty list).
In your main you are firstly reading the file and then write it: if the file doesn't exist it will throw you the exception. Probably, the first time you ran it, the file was present (maybe you have write the code to write the file first and then you have launch it).
so, two solutions...
First: change the order of your main.
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
Second: check if the file exist or not and then skip the read of it if it doesn't
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
//check if the file exist
File oFile = new File(filename);
if(oFile.exist()) {
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
UPDATE after comment:
public static void main(String[] aArgs) {
TextDB txtDB = new TextDB();
String filename = "professor.txt";
try {
//check if the file exist
File oFile = new File(filename);
if(!oFile.exist()) {
oFile.mkdirs(); //optional
oFile.createNewFile();
}
// read file containing Professor records.
ArrayList al = TextDB.readProfessors(filename);
for (int i = 0; i < al.size(); i++) {
Professor prof = (Professor) al.get(i);
System.out.println("Name " + prof.getName());
System.out.println("Contact " + prof.getContact());
}
Professor p1 = new Professor("Joseph", "jos#ntu.edu.sg", 67909999);
// al is an array list containing Professor objs
al.add(p1);
// write Professor record/s to file.
TextDB.saveProfessors(filename, al);
} catch (IOException e) {
System.out.println("IOException > " + e.getMessage());
}
}
Related
I am reading a file with a disease name and its remedies. Therefore, i want to save the name as key and remedies in a set as the value. How can i reach that? It seems there is some problems in my code.
public static HashMap<String,Set<String>> disease = new HashMap <> ();
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner (new File ("diseases.txt"));
while (fin.hasNextLine()) {
HashSet <String> remedies = null;
String [] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0],remedies);
}
fin.close();
}catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
try {fin.close();} catch(Exception e) {}
}
Set <String> result = disease.get("thrombosis");
display(result);
public static <T> void display (Set<T> items) {
if (items == null)
return;
int LEN = 80;
String line = "[";
for (T item:items) {
line+= item.toString() + ",";
if (line.length()> LEN) {
line = "";
}
}
System.out.println(line + "]");
}
here is my code
cancer,pain,swelling,bleeding,weight loss
gout,pain,swelling
hepatitis A,discoloration,malaise,tiredness
thrombosis,high heart rate
diabetes,frequent urination
and here is what the txt contains.
In your code , you haven't initialized the remedies HashSet(thats why it is throwing NullPointerException at line number 14).
and second issue is : i is getting incremented by 1 and you are not checking with size of your pats array ( i > parts.length) .
I edited your code :
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<String>();
String[] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()&&parts.length>i) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0], remedies);
}
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.io.File;
import java.util.Set;
public class Solution {
public static HashMap<String, Set<String>> disease = new HashMap<>();
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner (new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet <String> remedies = new HashSet<>();
String [] parts = fin.nextLine().split(",");
for (int i=1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
disease.put(parts[0],remedies);
}
fin.close();
}catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
try {fin.close();} catch(Exception e) {}
}
Set <String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display(Set<T> items) {
if (items == null)
return;
int LEN = 80;
String line = "[";
for (T item : items) {
line += item.toString() + ",";
if (line.length() > LEN) {
line = "";
}
}
System.out.println(line + "]");
}
}
Here is full working code. As suggested by #Pratik that you forget to initialize HashSet that's why NullPointerException error was coming.
You have a few issues here:
no need for inner while loop (while (fin.hasNext()) {) - instead use `for(int i=1; i
HashSet <String> remedies = null; - this means the set is not initialized and we cannot put items in it - nede to change to: HashSet<String> remedies = new HashSet<>();
It is better practice to close() the file in the finally part
The 'display' method will delete the line (if it is longer than 80 characters) before printing it.
it is better to use StringBuilder when appending strings
So the corrected code would be:
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class TestSOCode {
public static HashMap<String,Set<String>> disease = new HashMap<>();
private static int LINE_LENGTH = 80;
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<>();
String[] parts = fin.nextLine().split(",");
disease.put(parts[0], remedies);
for (int i = 1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
fin.close();
} catch (Exception e) {
System.out.println("Error when closing file: " + e.getMessage());
}
}
Set<String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display (Set<T> items) {
if (items == null)
return;
StringBuilder line = new StringBuilder("[");
int currentLength = 1; // start from 1 because of the '[' char
for (T item:items) {
String itemStr = item.toString();
line.append(itemStr).append(",");
currentLength += itemStr.length() + 1; // itemStr length plus the ',' char
if (currentLength >= LINE_LENGTH) {
line.append("\n");
currentLength = 0;
}
}
// replace last ',' with ']'
line.replace(line.length() - 1, line.length(), "]");
System.out.println(line.toString());
}
}
I'm doing a Phone Directory project and we have to read from a directory file telnos.txt
I'm using a Scanner to load the data from the file telnos.txt, using a loadData method from a previous question I asked here on StackOverflow.
I noticed attempts to find a user always returned Not Found, so I added a few System.out.printlns in the methods to help me see what was going on. It looks like the scanner isn't reading anything from the file. Weirdly, it is printing the name of the file as what should be the first line read, which makes me think I've missed something very very simple here.
Console
run:
telnos.txt
null
loadData tested successfully
Please enter a name to look up: John
-1
Not found
BUILD SUCCESSFUL (total time: 6 seconds)
ArrayPhoneDirectory.java
import java.util.*;
import java.io.*;
public class ArrayPhoneDirectory implements PhoneDirectory {
private static final int INIT_CAPACITY = 100;
private int capacity = INIT_CAPACITY;
// holds telno of directory entries
private int size = 0;
// Array to contain directory entries
private DirectoryEntry[] theDirectory = new DirectoryEntry[capacity];
// Holds name of data file
private final String sourceName = "telnos.txt";
File telnos = new File(sourceName);
// Flag to indicate whether directory was modified since it was last loaded or saved
private boolean modified = false;
// add method stubs as specified in interface to compile
public void loadData(String sourceName) {
Scanner read = new Scanner("telnos.txt").useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else
telno = read.nextLine();
add(name, telno);
i++;
}
}
public String lookUpEntry(String name) {
int i = find(name);
String a = null;
if (i >= 0) {
a = name + (" is at position " + i + " in the directory");
} else {
a = ("Not found");
}
return a;
}
public String addChangeEntry(String name, String telno) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setNumber(telno);
} else {
add(name, telno);
}
}
return null;
}
public String removeEntry(String name) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setName(null);
i.setNumber(null);
}
}
return null;
}
public void save() {
PrintWriter writer = null;
// writer = new PrintWriter(FileWriter(sourceName));
}
public String format() {
String a;
a = null;
for (DirectoryEntry i : theDirectory) {
String b;
b = i.getName() + "/n";
String c;
c = i.getNumber() + "/n";
a = a + b + c;
}
return a;
}
// add private methods
// Adds a new entry with the given name and telno to the array of
// directory entries
private void add(String name, String telno) {
System.out.println(name);
System.out.println(telno);
theDirectory[size] = new DirectoryEntry(name, telno);
size = size + 1;
}
// Searches the array of directory entries for a specific name
private int find(String name) {
int result = -1;
for (int count = 0; count < size; count++) {
if (theDirectory[count].getName().equals(name)) {
result = count;
}
System.out.println(result);
}
return result;
}
// Creates a new array of directory entries with twice the capacity
// of the previous one
private void reallocate() {
capacity = capacity * 2;
DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
System.arraycopy(theDirectory, 0, newDirectory,
0, theDirectory.length);
theDirectory = newDirectory;
}
}
ArrayPhoneDirectoryTester.java
import java.util.Scanner;
public class ArrayPhoneDirectoryTester {
public static void main(String[] args) {
//create a new ArrayPhoneDirectory
PhoneDirectory newTest = new ArrayPhoneDirectory();
newTest.loadData("telnos.txt");
System.out.println("loadData tested successfully");
System.out.print("Please enter a name to look up: ");
Scanner in = new Scanner(System.in);
String name = in.next();
String entryNo = newTest.lookUpEntry(name);
System.out.println(entryNo);
}
}
telnos.txt
John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231
In your code:
Scanner read = new Scanner("telnos.txt");
Is not going to load file 'telnos.txt'. It is instead going to create a Scanner object that scans the String "telnos.txt".
To make the Scanner understand that it has to scan a file you have to either:
Scanner read = new Scanner(new File("telnos.txt"));
or create a File object and pass its path to the Scanner constructor.
In case you are getting "File not found" errors you need to check the current working directory. You could run the following lines and see if you are indeed in the right directory in which the file is:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
You need to also catch the FileNotFoundException in the function as follows:
public void loadData(String sourceName) {
try {
Scanner read = new Scanner(new File("telnos.txt")).useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else {
telno = read.nextLine();
add(name, telno);
}
i++;
}
}catch(FileNotFoundException ex) {
System.out.println("File not found:"+ex.getMessage);
}
}
You are actually parsing the filename not the actual file contents.
Instead of:
new Scanner("telnos.txt")
you need
new Scanner( new File( "telnos.txt" ) )
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
So I have a file that has names along with 11 popularity ranks which looks like this. <--- (this is a link) I am a bit confused on what I am suppose to do with this next part that I have for my assignment. Generally I have a name app that looks like this:
public class Name{
private String givenName;
private int[] ranks = new int[11];
public Name(String name, int[] popularityRanks){
givenName = name;
for (int i = 0; i < 11; i++){
ranks[i] = popularityRanks[i];
}
}
public String getName(){
return givenName;
}
public int getPop(int decade){
if (decade >= 1 && decade <= 11){
return ranks[decade];
}
else{
return -1;
}
}
public String getHistoLine(int decade){
String histoLine = ranks[decade] + ": ";
return histoLine;
}
public String getHistogram(){
String histogram = "";
for (int i = 0; i < 11; i++){
histogram += ranks[i] + ": " + this.getHistoLine(i)
+ "\n";
}
return histogram;
}
}
It is not finished for the getHistoLine but that doesn't have anything to do with what I am trying to do. Generally I want to take these names in from the file and create an array of list.
How he describes it:
Create the array in main, pass it to the readNamesFile method and let that method fill it with Name objects
Test this, by printing out various names and their popularity rankings
For example, if main named the array, list, then upon return from the readNamesFile method do something like:
System.out.println( list[0].getName() + list[0].getPop(1) );
This is what my main looks like:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class NameApp{
public static void main(String[] args){
Name list[] = new Name()
}
private static void loadFile(){
Scanner inputStream = null;
String fileName = "names.txt";
try {
inputStream = new Scanner (new File(fileName));
}
catch (FileNotFoundException e){
System.out.println("Error opening file named: " + fileName);
System.out.println("Exiting...");
}
while (inputStream.hasNext()){
}
}
}
I am just a bit confused how I can take the name have it send to the Name object list[] and then take the popularity ranks and send it to the Name object list[]. So when I call
list[0].getName()
it will just call the name for one of the lines... Sorry I am a bit new to the java language. Thanks in advance
You need to create a Name list correctly. I would use a List since you don't know how many names there will be;
public static void main(String[] args){
List<Name> list = new ArrayList<Name>();
loadFile();
System.out.println(list.get(0).getPop());
}
private static void loadFile(){
Scanner inputStream = null;
String fileName = "names.txt";
try {
inputStream = new Scanner (new File(fileName));
}
catch (FileNotFoundException e){
System.out.println("Error opening file named: " + fileName);
System.out.println("Exiting...");
}
while (inputStream.hasNext()){
// givenName = something
// ranks = something;
list.add(new Name(givenName, ranks);
}
}
Assuming each line is something like this (from your deleted comment)
A 1 234 22 43 543 32 344 32 43
Your while loop can be something like this
while (inputStream.hasNextLIne()){
String line = inputStream.nextLine();
String tokens = line.split("\\s+");
String givenName = tokens[0];
int[] numList = new int[tokens.lenth - 1];
for (int i = 1; i < tokens.length; i++){
numList[i - 1] = Integer.parseInt(tokens[i].trim());
}
list.add(new Name(givenName, numList);
}
I have 2 files where 1(OrderCatalogue.java) reads in contents of a external file and 2(below). But I'm having the "FileNotFoundException must be caught or declard to be thrown" error for this line "OrderCatalogue catalogue= new OrderCatalogue();" and I understand that because its not in a method. But if i try puting it in a method, the code under the "getCodeIndex" and "checkOut" methods can't work with the error message of "package catalogue does not exist". Anyone has any idea how i can edit my code to make them work? Thank you!!
public class Shopping {
OrderCatalogue catalogue= new OrderCatalogue();
ArrayList<Integer> orderqty = new ArrayList<>(); //Create array to store user's input of quantity
ArrayList<String> ordercode = new ArrayList<>(); //Create array to store user's input of order number
public int getCodeIndex(String code)
{
int index = -1;
for (int i =0;i<catalogue.productList.size();i++)
{
if(catalogue.productList.get(i).code.equals(code))
{
index = i;
break;
}
}
return index;
}
public void checkout()
{
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Your order:");
for(int j=0;j<ordercode.size();j++)
{
String orderc = ordercode.get(j);
for (int i =0;i<catalogue.productList.size();i++)
{
if(catalogue.productList.get(i).code.equals(orderc))
{
System.out.print(orderqty.get(j)+" ");
System.out.print(catalogue.productList.get(i).desc);
System.out.print(" # $"+df.format(catalogue.productList.get(i).price));
}
}
}
}
And this is my OrderCatalogue file
public OrderCatalogue() throws FileNotFoundException
{
//Open the file "Catalog.txt"
FileReader fr = new FileReader("Catalog.txt");
Scanner file = new Scanner(fr);
while(file.hasNextLine())
{
//Read in the product details in the file
String data = file.nextLine();
String[] result = data.split("\\, ");
String code = result[0];
String desc = result[1];
String price = result[2];
String unit = result[3];
//Store the product details in a vector
Product a = new Product(desc, code, price, unit);
productList.add(a);
}
It seems the OrderCatalogue constructor throws FileNotFoundException. You can initialize catalogue inside Shopping constructor and catch the exception or declare it to throw FileNotFoundException.
public Shopping() throws FileNotFoundException
{
this.catalogue= new OrderCatalogue();
or
public Shopping()
{
try{
this.catalogue= new OrderCatalogue();
}catch(FileNotFoundException e)
blah blah
}
I'm making a province sorter, and the requirement is that I must leave the main class as is, and make a private class called Munge, i've been at this for hours and changed my code hundreds of times, basically it reads from a text file that looks like this
Hamilton, Ontario
Toronto, Ontario
Edmonton, Alberta
Red Deer, Alberta
St John's, Newfoundland
and needs to be output like this
Alberta; Edmonton, Red Deer
Ontario; Hamilton, Toronto
Newfoundland; St John's
my main class is unchangeable and looks like this
public class Lab5 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
if(args.length < 2) {
System.err.println("Usage: java -jar lab5.jar infile outfile");
System.exit(99);
}
Munge dataSorter = new Munge(args[0], args[1]);
dataSorter.openFiles();
dataSorter.readRecords();
dataSorter.writeRecords();
dataSorter.closeFiles();
}
}
and the Munge class i've made looks like this
package lab5;
import java.io.File;
import java.util.Scanner;
import java.util.Formatter;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
public class Munge
{
private String inFileName, outFileName;
private Scanner inFile;
private Formatter outFile;
private int line = 0;
private String[] data;
public Munge(String inFileName, String outFileName)
{
this.inFileName = inFileName;
this.outFileName = outFileName;
data = new String[100];
}
public void openFiles()
{
try
{
inFile = new Scanner(new File(inFileName));
File file = new File("input.txt");
SortedMap<String, List<String>> map = new TreeMap<String, List<String>>();
Scanner scanner = new Scanner(file).useDelimiter("\\n");
while (scanner.hasNext()) {
String newline = scanner.next();
if (newline.contains(",")) {
String[] parts = newline.split(",");
String city = parts[0].trim();
String province = parts[1].trim();
List<String> cities = map.get(province);
if (cities == null) {
cities = new ArrayList<String>();
map.put(province, cities);
}
if (!cities.contains(city)) {
cities.add(city);
}
}
}
for (String province : map.keySet()) {
StringBuilder sb = new StringBuilder();
sb.append(province).append(": ");
List<String> cities = map.get(province);
for (String city : cities) {
sb.append(city).append(", ");
}
sb.delete(sb.length() - 2, sb.length());
String output = sb.toString();
System.out.println(output);
}
}
catch(FileNotFoundException exception)
{
System.err.println("File not found.");
System.exit(1);
}
catch(SecurityException exception)
{
System.err.println("You do not have access to this file.");
System.exit(1);
}
try
{
outFile = new Formatter(outFileName);
}
catch(FileNotFoundException exception)
{
System.err.println("File not found.");
System.exit(1);
}
catch(SecurityException exception)
{
System.err.println("You do not have access to this file.");
System.exit(1);
}
}
public void readRecords()
{
while(inFile.hasNext())
{
data[line] = inFile.nextLine();
System.out.println(data[line]);
line++;
}
}
public void writeRecords()
{
for(int i = 0; i < line; i++)
{
String tokens[] = data[i].split(", ");
Arrays.sort(tokens);
for(int j = 0; j < tokens.length; j++)
outFile.format("%s\r\n", tokens[j]);
}
}
public void closeFiles()
{
if(inFile != null)
inFile.close();
if(outFile != null)
outFile.close();
}
}
you'll have to excuse my brackets, there formatted correctly in netbeans but i had to move the bottom ones over to keep it in the codeblock
As I think this is homework I'll avoid giving you a solution but give some hints of what to do.
When you have read a line it consists of City, Province. So the first thing you need to do is split the string into two parts. The second part is the province and the first is the city. You need to make a collection for each province and store the city in the correct province collection.
Once you have that you sort the names of the found provinces, and iterate through them. Sort the cities for the province and then output the province name and each city name.
Useful classes could be will be HashMap, TreeMap, List, Collections (has sort methods).
Hope that helps to get you further, otherwise try to be more specific where you are stuck.