如何在数据写入后打开txt文件?

时间:2018-04-14 11:09:54

标签: java file file-io file-handling fileinputstream

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);
        }
    }
}

因此,该程序从 flight.dat 读取数据,并将数据写入 output.txt 。之后,我必须手动打开&#34; output.txt &#34;用于检查数据是否已写入的文件。有没有办法在java程序结束时运行 output.txt 文件(因为它被双击)?如果有这样的方式,是否可以根据需要运行任何文件(也许是一个mp3文件)?还有一件事,我的代码有什么建议可以让它变得更好吗?谢谢大家的帮助。 :)

1 个答案:

答案 0 :(得分:0)

查看https://docs.oracle.com/javase/8/docs/api/java/awt/Desktop.html

在您的特定情况下,这可能会起到作用:

int