import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class OutputToFile {
public static void main(String[] args) {
ArrayList<Flight> flightList = new ArrayList<Flight>();
try {
BufferedReader filein = new BufferedReader(new FileReader(new File("flight.dat")));
PrintWriter fileout = new PrintWriter(new FileWriter("output.txt"));
String line;
String from = null;
String to = null;
String flightNo = null;
String date = null;
String departure = null;
if (filein != null) { // not null if file exist
while ((line = filein.readLine()) != null) { //has more line to read
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
from = st.nextToken();
to = st.nextToken();
flightNo = st.nextToken();
date = st.nextToken();
departure = st.nextToken();
}
Flight f = new Flight(from, to, flightNo, date, departure);
flightList.add(f);
}
}
fileout.println("Total number of flights :"+ flightList.size());
fileout.println("== Flight Plan ==");
for (Flight f: flightList) {
fileout.println();
fileout.println("From : "+ f.getFrom());
fileout.println("To : "+ f.getTo());
fileout.println("Flight Number : "+ f.getFlightNum());
fileout.println("Date : "+ f.getDate());
fileout.println("Departure Time : "+ f.getDepartureTime());
}
filein.close();
fileout.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
So, this program reads data from flight.dat and write the data into output.txt. After that, I have to manually open up the "output.txt" file to check if data has been written or not. Is there a way to make output.txt file to be run (as it were double clicked) by the end of the java program? If there is such a way, is it possible to also run any file as desired (maybe an mp3 file)? One more thing, is there any recommendation on my code to make it better? Thank you guys for all your help. :)
Check out https://docs.oracle.com/javase/8/docs/api/java/awt/Desktop.html
In your particular case, this might do the trick:
Desktop.getDesktop().open(new File("output.txt"));