The program I am writing will sort a hospital record that comes in a text file. The format of the text file is lastname,firstname,age,roomnumber, it will look exactly like this :
Franklin,Benjamin,74,18
Hamilton,Alexander,25,6
Thatcher,Margaret,65,3
Nixon,Richard,45,7
and has to be printed with a certain format, but the user will specify how they are sorted. The format will look like this when sorted by last name:
Last First Age Room
Coolidge Calvin 24 27
Franklin Benjamin 74 8
Hamilton Alexander 50 123
Nixon Richard 45 7
I have been stuck on trying to find a way to store the lines and still be able to print out the lines together in order to keep the information together.
The Program has to be called through command-line and at the same time the program is called the user must specify the input file as the first argument (args[0]) and how to sort it as the second argument (args[1]).
I have tried a few different ways but I keep getting stuck in the same place, what would be the best way to approach this?
This is the current code btw. and the comment blocks is old code I have tried and keep it around, just in case.
import java.io.*;
import java.util.*;
public class PatientRecord {
public static void main(String args[])
{
System.out.println("Servando Hernandez");
System.out.println("Patient sorting Program.");
//
// Scanner scan = null;
// try
// {
// scan = new Scanner(new File(args[0]));
// }
// catch (FileNotFoundException e)
// {
// System.err.println("File path \"" + args[0] + "\" not found.");
// System.exit(0);
// }
//
// ArrayList<String> lines=new ArrayList<String>();
//
// while(scan.hasNextLine())
// lines.add(scan.nextLine());
//
// if(!(args.length == 0))
// {
// if(args[1] == lastname)
// {
// sortByLastName();
// }
// else if(args[1] == firstname)
// {
// sortByLastName();
// }
// else if(args[1] == age)
// {
// sortByAge();
// }
// else if(args[1] == roomnumber)
// {
// sortByRoomNumber();
// }
// }
//
List<Patient> patients = new ArrayList<>();
while(scan.hasNextLine())
{
String[] values= scan.nextLine().split(",");
patients.add(new Patient())
}
String sortType= args[1]
switch(sortType))
{
case "firsname":
break;
case "lastname":
break;
case "age":
break;
case "roomnumber":
break;
}
}
// static String sortByLastName()
// {
// Collections.sort(lines);
//
// for(String x : lines)
// System.out.println(x);
// }
class Patient
{
String firstName;
String lastName;
int age;
int roomNumber;
}
You should write a custom Comparator, let's call it PatientComparator. I will not implement the compare method completely, that's your job :-)
class PatientComparator implements Comparator<Patient> {
String sortType;
public PatientComparator(String sortType) {
this.sortType = sortType;
}
#Override
public int compare(Patient a, Patient b) {
// TODO: write your switch case here
return a.firstName.compareTo(b.firstName);
}
Then, you can sort the Patients using your own Comparator:
Collections.sort(patients, new PatientComparator(arg[1]));
Well I would start by dividing your exercise into two parts:
1- Calling the program through command-line with args[0]. Going through the file and showing the contents to the user (by respecting your format).
2- Add sorting to your script (this can be done in many ways; in general by overriding the compare method). Do step 1,sort with regarding to arg[1] and then the output.
To get you started I have done step 1 for you without doing any formatting on the output.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Test3 {
//You will store each line as an array of strings
//then you store the lines in a list of arrays of strings
public static ArrayList<String[]> mainList=new ArrayList<String[]>();
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(args[0]));
try {
//reading each line from the input file
String line = br.readLine();
//spliting the line by comma (,) which will return
//an array of strings - our names and numbers in string format
while (line != null) {
String[] lineElements=line.split(",");
line = br.readLine();
mainList.add(lineElements);
}
} finally {
br.close();
}
//showing to the user
for (String[] line :mainList){
for (String x:line){
System.out.print(x+" ");
}
System.out.println("");
}
}
}
You simply compile with: javac name.java
Then you simply specify the file's location when you actually run it: java name /path/to/your/file/
I have run it using your sample file and I get this in the console (you simply have to format the output):
Franklin Benjamin 74 18
Hamilton Alexander 25 6
Thatcher Margaret 65 3
Nixon Richard 45 7
There is much more to do but I think this is a great start!
Related
I am trying to find the String "5464" in a csv document then have it return all of the values under that String (same number of Delimiters from the start of the line), until reaching the end of the list (no more values in the column). Any help would be sincerely appreciated.
import javax.swing.JOptionPane;
public class SearchNdestroyV2 {
private static Scanner x;
public static void main(String[] args) {
String filepath = "tutorial.txt";
String searchTerm = "5464"
readRecord(searchTerm,filepath);
}
public void readRecord(String searchTerm, String filepath)
{
boolean found = false;
String ID = ""; String ID2 = ""; String ID3 = "";
}
try
{
x = new Scanner(new File(filepath));
x.useDelimeter("[,\n]");
while(x.hasNext() && !found )
{
ID = x.next();
ID2 = x.nextLine();
ID3 = x.nextLine();
if(ID.equals(searchTerm))
{
found = true;
}
}
if (found)
{
JOptionPane.showMessageDialog(null,"ID: " + ID + "ID2: " + ID2 + "ID3: "+ID3);
}
}
else
{
JOptionPane.showMessageDialog(null, "Error:");
}
catch(Exception e)
{
}
{
}
I'm not exactly sure of what you mean. The way I read your question:
You want to locate a specific String ("5464") that is contained within a specific column within a comma (,) delimited CSV file. If this specific string (search term) is found then retrieve all other values contained within the same column for the rest of the CSV file records from the point of location. Here is how:
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class SearchNDestroyV2 {
private Scanner fileInput;
public static void main(String[] args) {
// Do this if you don't want to deal with statics
new SearchNDestroyV2().startApp(args);
}
private void startApp(String[] args) {
String filepath = "tutorial.txt";
String searchTerm = "5464";
readRecord(searchTerm, filepath);
}
public void readRecord(String searchTerm, String filepath) {
try {
fileInput = new Scanner(new File(filepath));
// Variable to hold each file line data read.
String line;
// Used to hold the column index value to
// where the found search term is located.
int foundColumn = -1;
// An ArrayList to hold the column values retrieved from file.
ArrayList<String> columnList = new ArrayList<>();
// Read file to the end...
while(fileInput.hasNextLine()) {
// Read in file - 1 trimmed line per iteration
line = fileInput.nextLine().trim();
//Skip blank lines (if any).
if (line.equals("")) {
continue;
}
// Split the curently read line into a String Array
// based on the comma (,) delimiter
String[] lineParts = line.split("\\s{0,},\\s{0,}"); // Split on any comma/space situation.
// Iterate through the lineParts array to see if any
// delimited portion equals the search term.
for (int i = 0; i < lineParts.length; i++) {
/* This IF statement will always accept the column data and
store it if the foundColumn variable equals i OR the current
column data being checked is equal to the search term.
Initially when declared, foundColumn equals -1* and will
never equal i unless the search term is indeed found. */
if (foundColumn == i || lineParts[i].equals(searchTerm)) {
// Found a match
foundColumn = i; // Hold the Coloumn index number of the found item.
columnList.add(lineParts[i]); // Add the found ite to the List.
break; // Get out of this loop. Don't need it anymore for this line.
}
}
}
if (foundColumn != -1) {
System.out.println("Items Found:" + System.lineSeparator() +
"============");
for (String str : columnList) {
System.out.println(str);
}
}
else {
JOptionPane.showMessageDialog(null, "Can't find the Search Term: " + searchTerm);
}
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
If however, what you want is to search through the CSV file and as soon as any particular column equals the Search Term ("5464") then simply store the CSV line (all its data columns) which contains that Search Term. Here is how:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SearchNDestroyV2 {
/* A JFrame used as Parent for displaying JOptionPane dialogs.
Using 'null' can allow the dialog to open behind other open
applications (like the IDE). This ensures that it will be
displayed above all other applications at center screen. */
JFrame iFRAME = new JFrame();
{
iFRAME.setAlwaysOnTop(true);
iFRAME.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iFRAME.setLocationRelativeTo(null);
}
public static void main(String[] args) {
// Do this if you don't want to deal with statics
new SearchNDestroyV2().startApp(args);
}
private void startApp(String[] args) {
String filepath = "tutorial.txt";
String searchTerm = "5464";
ArrayList<String> recordsFound = readRecord(searchTerm, filepath);
/* Display any records found where a particular column
matches the Search Term. */
if (!recordsFound.isEmpty()) {
System.out.println("Records Found:" + System.lineSeparator()
+ "==============");
for (String str : recordsFound) {
System.out.println(str);
}
}
else {
JOptionPane.showMessageDialog(iFRAME, "Can't find the Search Term: " + searchTerm);
iFRAME.dispose();
}
}
/**
* Returns an ArrayList (of String) of any comma delimited CSV file line
* records which contain any column matching the supplied Search Term.<br>
*
* #param searchTerm (String) The String to search for in all Record
* columns.<br>
*
* #param filepath (String) The CSV (or text) file that contains the data
* records.<br>
*
* #return ({#code ArrayList<String>}) An ArrayList of String Type which
* contains the file line records where any particular column
* matches the supplied Search Term.
*/
public ArrayList<String> readRecord(String searchTerm, String filepath) {
// An ArrayList to hold the line(s) retrieved from file
// that match the search term.
ArrayList<String> linesList = new ArrayList<>();
// Try With Resourses used here to auto-close the Scanner reader.
try (Scanner fileInput = new Scanner(new File(filepath))) {
// Variable to hold each file line data read.
String line;
// Read file to the end...
while (fileInput.hasNextLine()) {
// Read in file - 1 trimmed line per iteration
line = fileInput.nextLine().trim();
//Skip blank lines (if any).
if (line.equals("")) {
continue;
}
// Split the curently read line into a String Array
// based on the comma (,) delimiter
String[] lineParts = line.split("\\s{0,},\\s{0,}"); // Split on any comma/space situation.
// Iterate through the lineParts array to see if any
// delimited portion equals the search term.
for (int i = 0; i < lineParts.length; i++) {
if (lineParts[i].equals(searchTerm)) {
// Found a match
linesList.add(line); // Add the found line to the List.
break; // Get out of this loop. Don't need it anymore for this line.
}
}
}
}
catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
return linesList; // Return the ArrayList
}
}
Please try to note the differences between the two code examples. In particular how the file reader (Scanner object) is closed, etc.
I write a program and need to generate results for different input (integer) values. which i have to read some integer numbers from several text files and store them in these variables.
choice
numofNodes
numofPoints
in each file there might be multiple numbers that should be assigned to one of above variables, for example:
First text file contains five values for first variables and other two variables have one value on separate lines like below:
1 2 3 4 5
60
50
Second text file contains five values for second variables and other two variables have one value on separate lines like below:
1
40 50 60 70 80
50
and so on..
I have no idea how to read them from text files.
any helps will be appreciated.
Here's my Main class:
public static void main(String[] args)throws InterruptedException {
// how to read numbers from different text files here
// and store them in these variables to call func method?
// int choice = ?
// int numofNode = ?
// int numofPoint = ?
path ob=new path(choice,numofNode,numofPoint);
ob.func();
}
put files path in a string array. then you can read the files by creating an instance of java.util.Scanner class that has several methods to read file content.
all you need is to use for and for-each loops to loop through your files and read them.
here's some code that i hope helps!
/**
* converts array of string numbers to array of integer numbers.
*
* #param numbers is array of strings
* #return an integer array which is parsed from <b>numbers</b>
*
*/
static int[] parseInt(String[] numbers) {
return Arrays.stream(numbers).mapToInt(Integer::parseInt).toArray();
}
public static void main(String[] args) {
// put input files path here
String[] name_and_path_of_files = {
"C:\\Users\\YOUR_USER\\Desktop\\input_1.txt",
"C:\\Users\\YOUR_USER\\Desktop\\input_2.txt"
};
// file reader
Scanner inputFileReader = null;
try {
// for all files
for (String fileInfo : name_and_path_of_files) {
// create reader object with file info
inputFileReader = new Scanner(new File(fileInfo));
int line_index = 0;
int choices[] = null;
int numofNodes[] = null;
int numofPoints[] = null;
// trying to read file content
while (inputFileReader.hasNext()) {
String separated_numbers[] = inputFileReader.nextLine().split(" ");
switch (line_index) {
case 0:
choices = parseInt(separated_numbers);
break;
case 1:
numofNodes = parseInt(separated_numbers);
break;
case 2:
numofPoints = parseInt(separated_numbers);
break;
}
line_index++;
}
for (int choice : choices) {
for (int numofPoint : numofPoints) {
for (int numofNode : numofNodes) {
path ob = new path(choice, numofNode, numofPoint);
ob.func();
}
}
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
if (inputFileReader != null) {
inputFileReader.close();
}
}
}
I have a log file and I am trying to parse the file in following way:
The file to be parsed looks like:
filename.......f1
This test is associated with file 1 - ignore it
filename.......f2
This test is associated with file 2 -ignore it
filename.......f3
This test is associated with file 3 - line 1 - do not ignore it
This test is associated with file 3 - line 2 - do not ignore it
filename.......f4
This test is associated with file 4 - ignore it
filename.......f5
This test is associated with file 5 - do not ignore it
Let's suppose we are macthing the text in file using Regx pattern as follows:
MATCHING_PATTERN1 - for "filename.......f[X]"
MATCHING_PATTERN2 - for "This test is associated with file [X] - do not ignore it"
I'm using following code:
package org.c2pfiscbk.tutorial;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TestLogParser {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
LogParser lp = new LogParser();
lp.logReader();
}
}
class LogParser {
public void logReader(){
File input = new File("file_location/fileName.log");
try {
Scanner scanner = new Scanner(input);
while(scanner.hasNext()){
String dLine = scanner.nextLine();
if (dLine.matches("MATCHING_PATTERN1")){
System.out.println(dLine);
}
else{
if (dLine.matches("MATCHING_PATTERN2")){
System.out.println(dLine);
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My output using above code is:
filename.......f1
filename.......f2
filename.......f3
This test is associated with file 3 - line 1 - do not ignore it
This test is associated with file 3 - line 2 - do not ignore it
filename.......f4
filename.......f5
This test is associated with file 5 - do not ignore it
Whereas, my requirment is:
filename.......f3
This test is associated with file 3 - line 1 - do not ignore it
This test is associated with file 3 - line 2 - do not ignore it
filename.......f5
This test is associated with file 5 - do not ignore it
Which means I am intrested only in the filenames (with MATCHING_PATTERN1) followed by certain text (with MATCHING_PATTERN2) along with the text (with MATCHING_PATTERN2) itself.
I don't want to use sed or egrep or any other external tool.
You need to create a boolean variable to say whether you need to print the first match (since you only want to print it once for all the associated pattern 2's). Then as the answers above suggest, you can then use a cache style variable to print the file name once.
String fileName=null;
boolean printFilename = false;
while(scanner.hasNext()){
String dLine = scanner.nextLine();
if (dLine.matches("MATCHING_PATTERN1")){
fileName = dLine;
printFilename = true;
}
else{
if (dLine.matches("MATCHING_PATTERN2")){
if (printFilename) {
System.out.println(fileName);
printFilename = false;
}
System.out.println(dLine);
}
}
}
Simply store the filename in some variable and print it only when you are in the
String fileName=null;
while(scanner.hasNext()){
String dLine = scanner.nextLine();
if (dLine.matches("MATCHING_PATTERN1")){
fileName = dname;
}
else{
if (dLine.matches("MATCHING_PATTERN2")){
System.out.println(fileName );
System.out.println(dLine);
}
}
}
Keep track of all the lines to print back, and eventually print them:
String currentHeader = scanner.nextLine();
List<String> followingLines = new ArrayList<>();
while(scanner.hasNext()){
String line = scanner.nextLine();
if (line.matches("MATCHING_PATTERN1")){
// new header, let's print the lines if there are lines to print
if(!followingLines.isEmpty()) {
System.out.println(currentHeader);
for(String followingLine : followingLines) {
System.out.println(followingLine);
}
}
// reset
currentHeader = line;
followingLines.clear();
} else if (line.matches("MATCHING_PATTERN2")){
followingLines.add(line);
}
}
// print last one
if(!followingLines.isEmpty()) {
System.out.println(currentHeader);
for(String followingLine : followingLines) {
System.out.println(followingLine);
}
}
You will have run a second loop to get your result
while(scanner.hasNext()){
String dLine = scanner.nextLine();
if (dLine.matches("MATCHING_PATTERN1")){
System.out.println(dLine);
String dLine2 = scanner.nextLine();
while(scanner.hasNext() && dLine2.matches("MATCHING_PATTERN2"){
System.out.println(dLine2);
}
}
}
Well your output is logical, since the first match makes it print any "filename.... f[X]", including the ones you don't want. Make the first match store the line in a variable instead or printing it, print that variable in the second match if it's not printed yet and it'll work as you want:
String cacheLine = "";
String lastPrintedCacheLine = "";
while(scanner.hasNext()){
String dLine = scanner.nextLine();
if (dLine.matches("MATCHING_PATTERN1")){
cacheLine = dLine;
} else if (dLine.matches("MATCHING_PATTERN2")){
if (! cacheLine.equals(lastPrintedCacheLine)) {
System.out.println(cacheLine);
lastPrintedCacheLine = cacheLine;
}
System.out.println(dLine);
}
}
Verified. However, the answer from Riggy works as well and costs less.
Note that your use of the {} block after the else is obsolete and you could simply use else if. Makes the code a little less messy imho.
I will write data into the text file in format like this:
Jonathan 09.5.2015 1
John 10.5.2015 4
Jonathan 11.5.2015 14
Jonathan 12.5.2015 15
Jonathan 13.5.2015 7
Tobias 14.5.2015 9
Jonathan 15.5.2015 6
The last number is hours. I need to make something where I can write two dates and name. For example - Jonathan 11.5.2015 and second date 15.5.2015. All I want to do is count hours between these dates. Output should looks like Jonathan 11.5.2014 - 15.5.2014 - 42 hours I don't have problem with GUI but I don't know the right way how to compute my result.
Assuming that you have to write a method that, given a text file in the above format, a name and two dates, returns the total hours attributed to that person between the two dates, your code can be made very simple:
public int totalHours(Iterable<String> input, String person, String date1, String date2) {
SimpleDateFormat sdf = new SimpleDateFormat("MM.dd.yyyy");
Date start = sdf.parse(date1);
Date end = sdf.parse(date2);
int total = 0;
for (String line : input) { // assuming each string in input is a line
String parts[] = line.split(" ");
if ( ! parts[0].equals(person)) continue; // ignore - not him
Date d = sdf.parse(parts[1]);
if (d.compareTo(end) > 0) break; // if dates are sorted, we're finished
if (d.compareTo(start) <= 0) total += Integer.parseInt(parts[2]);
}
return total;
}
This code assumes that your input is already split into lines. You write that you already know how to read from files, so this should not be an obstacle. The function would run a lot faster (for repeated queries) if you store all lines in a TreeMap, indexed by their dates. And even more efficient if you built a HashMap<String, TreeMap<Date, Integer> > from the file, where the strings would be people's names and the integers would be the hours on those dates.
Edit: one way of doing the file-reading part
There are many ways of reading files. The most standard is the one you describe in your comment. This is a modified version that makes minimal changes to the above totalHours (argument input is now an Iterable<String> instead of String[]). The code has been adapted from
Iterating over the content of a text file line by line - is there a best practice? (vs. PMD's AssignmentInOperand):
public class IterableReader implements Iterable<String> {
private BufferedReader r;
public IterableReader(String fileName) throws IOException {
r = new BufferedReader(new FileReader(fileName));
}
public Iterator<String> iterator() {
return new Iterator<String>() {
String nextLine = readAndIfNullClose();
private String readAndIfNullClose() {
try {
String line = r.readLine();
if (line == null) r.close();
return line;
} catch (IOException e) {
return null;
}
}
#Override
public boolean hasNext() {
return nextLine != null;
}
#Override
public String next() {
String line = nextLine;
nextLine = readAndIfNullClose();
return line;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
And you should now be able to call it as follows:
System.out.println("Hours worked by Bob from 11.5.2015 to 15.5.2015: "
+ totalHours(new IterableReader("inputfile.txt"),
"Bob", "11.5.2015", "15.5.2015"));
import java.io.*;
class Test{
BufferedReader f = null;
try{
f = new BufferedReader(new FileReader("youFile.txt"));
String something=null;
while((something=f.readLine())!=null){
String[] part= something.split(" ");
}
}catch(FileNotFoundException e){
e.getMessage();
}
}
After you split this code, you will get a array "part" with 3 index
per line, so you should convert to int or String depending what you
want to do. 0 = name 1 = hour 2 = this forever alone number :D
I am writing a method that will take in some command line arguments, validate them and if valid will edit an airport's code. The airport name and it's code are stored in a CSV file. An example is "Belfast,BHD". The command line arguments are entered as follows, java editAirport EA BEL Belfast, "EA" is the 2letter code that makes the project know that I want to Edit the code for an Airport, "BEL" is the new code, and Belfast is the name of the Airport.
When I have checked through the cla's and validated them I read through the file and store them in an ArrayList as, "Belfast,BEL". Then I want to update the text file by removing the lines from the text file and dumping in the arraylist, but I cannot figure out how to do it. Can someone show me a way using simple code (no advanced java stuff) how this is possible.
Here is my program
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class editAirport
{
public static void main(String [] args)throws IOException
{
String pattern = "[A-Z]{3}";
String line, line1, line2;
String[] parts;
String[] parts1;
boolean found1 = false, found2 = false;
File file = new File("Airports.txt"); // I created the file using the examples in the outline
Scanner in = new Scanner(file);
Scanner in1 = new Scanner(file);
Scanner in2 = new Scanner(file);
String x = args[0], y = args[1], z = args[2];
//-------------- Validation -------------------------------
if(args.length != 3) // if user enters more or less than 3 CLA's didplay message
JOptionPane.showMessageDialog(null, "Usage: java editAirport EA AirportCode(3 letters) AirportName");
else if(!(file.exists())) // if "Airports.txt" doesn't exist end program
JOptionPane.showMessageDialog(null, "Airports.txt does not exist");
else // if everything is hunky dory
{
if(!(x.equals("EA"))) //if user doesn't enter EA an message will be displayed
JOptionPane.showMessageDialog(null, "Usage: java editAirport EA AirportCode(3 letters) AirportName");
else if(!(y.matches(pattern))) // If the code doesn't match the pattern a message will be dislayed
JOptionPane.showMessageDialog(null, "Airport Code is invalid");
while(in.hasNext())
{
line = in.nextLine();
parts = line.split(",");
if(y.equalsIgnoreCase(parts[1]))
found1 = true; //checking if Airport code already is in use
if(z.equalsIgnoreCase(parts[0]))
found2 = true; // checking if Airport name is in the file
}
if(found1)
JOptionPane.showMessageDialog(null, "Airport Code already exists, Enter a different one.");
else if(found2 = false)
JOptionPane.showMessageDialog(null, "Airport Name not found, Enter it again.");
else
/*
Creating the ArrayList to store the name,code.
1st while adds the names and coses to arraylist,
checks if the name of the airport that is being edited is in the line,
then it adds the new code onto the name.
sorting the arraylist.
2nd for/while is printing the arraylist into the file
*/
ArrayList<String> airport = new ArrayList<String>();
while(in1.hasNext()) // 1st while
{
line1 = in1.nextLine();
if(line1.contains(z))
{
parts1 = line1.split(",");
parts1[1] = y;
airport.add(parts1[0] + "," + parts1[1]);
}
else
airport.add(line1);
}
Collections.sort(airport); // sorts arraylist
FileWriter aFileWriter = new FileWriter(file, true);
PrintWriter output = new PrintWriter(aFileWriter);
for(int i = 0; i < airport.size();)
{
while(in2.hasNext()) // 2nd while
{
line2 = in2.nextLine();
line2 = airport.get(i);
output.println(line2);
i++;
}
}
output.close();
aFileWriter.close();
}
}
}
}
The Airports.txt file is this
Aberdeen,ABZ
Belfast City,BHD
Dublin,DUB
New York,JFK
Shannon,SNN
Venice,VCE
I think your problem may lie in the two lines:
line2 = in2.nextLine();
line2 = airport.get(i);
this will overwrite the 'line2' in memory, but not in the file.