java.lang.RuntimeException:无法打开文件

时间:2015-04-20 04:08:06

标签: java junit runtimeexception

我有DataManager.javaExportBasicTest.java进行测试。

我无法让DataManager.java通过测试,即使它们看起来像是基本错误。

我尝试搞乱两个文件的目录以及我创建的名为ExportedFile.txt的文件,但我无法解决任何错误。

我有两个arrayLists类型<Passenger><Flight>,它们各有不同的部分。这些部分是我的长方法所引用的。

DataManager.java

import java.io.*;
import java.util.*;

public class DataManager {

    private static File fileName;
    private static Formatter fileFormatter;
    private static ArrayList<Flight> theFlights;
    private static ArrayList<Passenger> thePassengers;

    public static void exportData(String filename, ArrayList<Passenger> passengers, ArrayList<Flight> flights) {
        fileName = new File(filename);
        theFlights = flights;
        thePassengers = passengers;
        openFile();
        addFlights();
        addPassengers();
        closeFile();
    }

    public static void openFile(){
        try{
            fileFormatter = new Formatter(fileName);
            System.out.println("you created a file");
        }
        catch(Exception e){
            System.out.println("You have an error.");
        }
    }

    public static int AlertsCount(int i){
        return thePassengers.get(i).getAlerts().size();
    }//AlertsCount

    public static String listAlerts(int i){
        StringBuilder stringBuilder = new StringBuilder();      
        for(int z = 0;z<thePassengers.get(i).getAlerts().size();z++){
            stringBuilder.append(thePassengers.get(i).getAlerts().get(z) + System.getProperty("line.separator"));
        }
        String alerts = stringBuilder.toString();
        return alerts;
    }//listAlerts close

    public static int BookedFlightsCount(int i){
        return thePassengers.get(i).getBookedFlights().size();
    }//bookedFlightsCount close

    public static String listBookedFlights(int i){
        StringBuilder stringBuilder = new StringBuilder();      
        for(int z = 0;z<thePassengers.get(i).getBookedFlights().size();z++){
            stringBuilder.append(thePassengers.get(i).getBookedFlights().get(z).getSourceAirport() + " , " + 
                    thePassengers.get(i).getBookedFlights().get(z).getDestinationAirport() + " , " +
                    Integer.toString(thePassengers.get(i).getBookedFlights().get(z).getTakeOffTime()) + " , " +
                    Integer.toString(thePassengers.get(i).getBookedFlights().get(z).getLandingTime()) + System.getProperty("line.separator"));
        }
        String bookedFlights = stringBuilder.toString();
        return bookedFlights;
    }//listBookedFlights close

    public static int StandbyFlightsCount(int i){
        return thePassengers.get(i).getStandbyFlights().size();
    }//StandbyFlightsCount close

    public static String listStandbyFlights(int i){
        StringBuilder stringBuilder = new StringBuilder();      
        for(int z = 0;z<thePassengers.get(i).getStandbyFlights().size();z++){
            stringBuilder.append(System.getProperty("line.separator") + thePassengers.get(i).getStandbyFlights().get(z).getSourceAirport() + " , " + 
                    thePassengers.get(i).getStandbyFlights().get(z).getDestinationAirport() + " , " +
                    Integer.toString(thePassengers.get(i).getStandbyFlights().get(z).getTakeOffTime()) + " , " +
                    Integer.toString(thePassengers.get(i).getStandbyFlights().get(z).getLandingTime()));
        }
        String standbyFlights = stringBuilder.toString();
        return standbyFlights;
    }//listStandbyFlights close

    public static void addPassengers(){
            fileFormatter.format("%s%d", "#passCount ", thePassengers.size());

        for(int i = 0; i<thePassengers.size();i++){
        fileFormatter.format("%s%s%s%s%s%s%d%s%s%d%s%s%d%s",System.getProperty("line.separator"), "#newPass",System.getProperty("line.separator"), thePassengers.get(i).getFirstName()+" , ", thePassengers.get(i).getLastName(),System.getProperty("line.separator"),
                AlertsCount(i),System.getProperty("line.separator"), listAlerts(i), BookedFlightsCount(i),System.getProperty("line.separator"), listBookedFlights(i), StandbyFlightsCount(i), listStandbyFlights(i));
        }
    }//addPassengers close

    public static void addFlights(){
            fileFormatter.format("%s%d%s", "#flightCount ", theFlights.size(), System.getProperty("line.separator"));
        for(int i = 0;i<theFlights.size();i++){
            fileFormatter.format("%s%s%s , %s , %d , %d%s%d%s", "#newFlight",System.getProperty("line.separator"), theFlights.get(i).getSourceAirport(), theFlights.get(i).getDestinationAirport(), 
                    theFlights.get(i).getTakeOffTime(), theFlights.get(i).getLandingTime(), System.getProperty("line.separator"),theFlights.get(i).getCapacity(),System.getProperty("line.separator"));
        }
    }//addFlights close

    public static void closeFile(){
        fileFormatter.close();
    }//closeFile close


    //This function creates and writes data for a new file using the specifications ,
    //given earlier in order to store the data represented by those objects stored within the two ArrayLists.
}

ExportBasicTest.java

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

import junit.framework.Assert;

import org.junit.Test;


public class ExportBasicTest {

    @Test(timeout = 1000)
    public void exportExampleFile() 
    {
        ArrayList<Flight> flightList = new ArrayList<Flight>();

        Flight f1 = new Flight("MCO", "MIA", 800, 930, 8);
        Flight f2 = new Flight("MIA", "ATL", 1100, 1400, 23);
        Flight f3 = new Flight("ATL", "GNV", 1430, 1615, 15);

        flightList.add(f1);
        flightList.add(f2);
        flightList.add(f3);

        ArrayList<Passenger> passList = new ArrayList<Passenger>();

        Passenger p1 = new Passenger("Joshua", "Horton");
        Passenger p2 = new Passenger("Adam", "Smith");

        passList.add(p1);
        passList.add(p2);

        p1.addAlert("The 7:30 flight from BTR to GNV has been cancelled!");

        p1.bookFlight(f1);
        p1.bookFlight(f2);

        p2.bookFlight(f3);
        p2.addStandbyFlight(f1);
        p2.addStandbyFlight(f2);

        DataManager.exportData("ExportedFile.txt", passList, flightList);

        // This file, given the initial setup, should almost perfectly match the provided example file.
        Assert.assertEquals("File contents are not as expected!", true, matchFiles("ProjStage3BasicFile.txt", "ExportedFile.txt"));
    }

    // Checks if the files match by directly comparing their exact contents.
    private boolean matchFiles(String expected, String actual)
    {
        Scanner inFile1;
        Scanner inFile2;

        try
        {
            inFile1 = new Scanner(new File(expected));
            inFile2 = new Scanner(new File(actual));
        }
        catch(IOException e)
        {
            throw new RuntimeException("Cannot open files!", e);
        }

        ArrayList<String> expectedLines = new ArrayList<String>();
        ArrayList<String> actualLines = new ArrayList<String>();

        while(inFile1.hasNextLine())
        {
            expectedLines.add(inFile1.nextLine());
        }

        while(inFile2.hasNextLine())
        {
            actualLines.add(inFile2.nextLine());
        }

        // Erase a trailing blank line at the file's end; I don't mind that.
        if(actualLines.get(actualLines.size() - 1).trim().equals(""))
        {
            actualLines.remove(actualLines.size() - 1);
        }

        return expectedLines.equals(actualLines);
    }

}

1 个答案:

答案 0 :(得分:0)

您需要将路径传递给文件,而不仅仅是使用文件名的名称。

您的匹配文件方法会抛出错误,因为它无法打开您传递的文件名。要使用当前工作目录,请使用./,如&#34; ./ filename.txt&#34;而不是&#34; filename.txt&#34;

您始终可以使用java.nio.file.Files

检查路径是否存在
if(Files.exists(path)){...}
相关问题