当前位置: 首页 > 知识库问答 >
问题:

为什么即使在Java中使用close()方法,也会出现“Resource leak:””错误?

宋育
2023-03-14

为什么即使在Java中使用close()方法,也会出现“Resource leak:”错误?

我把整个代码和注释放在哪里,在哪里得到错误信息,在哪里关闭Scanner方法

我使用Eclipse,Java13。

这是密码。

import java.util.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;

public class VehicleTest {
  public static void main(String[] args) {
      VehicleTest vtest = new VehicleTest();
    try {
      vtest.menuLoop();
    } catch(IOException e) {
      System.out.println("IO Exception!");
      System.exit(1);
    } catch(CloneNotSupportedException e) {
      System.out.println("CloneNotSupportedException");
      System.exit(1);
    }
  }

  private void menuLoop() throws IOException, CloneNotSupportedException {
    Scanner scan = new Scanner(System.in);
    ArrayList<Vehicle> arr=new ArrayList<Vehicle>();
    Vehicle vehicle;

/** Deleted the hard coded adds so it doesn't add same types of cars
 *  everytime
 */

    java.io.File file = new java.io.File("Vehicles.txt");
    Scanner in = new Scanner(file).useLocale(Locale.US);
    in.useDelimiter(",");    //** This is where I get the resource leak error message **//
    while (in.hasNext()) {
        try {
              String vehClass = in.next();                
              Class veh1 = Class.forName(vehClass);
            Vehicle veh = (Vehicle)veh1.
                    getDeclaredConstructor().newInstance();
            arr.add(veh);
            veh.readData(in);
        } catch (Exception e) { 
            System.out.print("Exception");
            System.exit(0);
            }
    }

    while(true) {
      System.out.println("1...................................New car");
      System.out.println("2...............................New bicycle");
      System.out.println("3......................Find vehicle by name");
      System.out.println("4..............Show data about all vehicles");
      System.out.println("5.......Change direction of a given vehicle");
      System.out.println("6.........................Test clone method");
      System.out.println("7..................Test driveable interface");
      System.out.println("8..............................Exit program");
      System.out.println("...............................Your choice?");
      int choice = scan.nextInt();
      String name;

      switch (choice) {
      case 1:
        arr.add(new Car());
        vehicle = arr.get(arr.size() - 1);
        try {
            vehicle.setAllFields();
          } catch(Exception e) {
            System.out.println("Wrong input!");
            System.exit(1);
          }
        break;
      case 2:
        arr.add(new Bicycle());
        vehicle = arr.get(arr.size() - 1);
        try {
            vehicle.setAllFields();
          } catch(Exception e) {
            System.out.println("Wrong input!");
            System.exit(1);
          }
        break;
      case 3:
        System.out.println("Name of vehicle: ");
        name = scan.next();
        for(Vehicle v : arr) {
            if(v.getName() != null && 
                    (v.getName().compareToIgnoreCase(name) == 0)) {
                        System.out.println(v);
            }
        }
        break;
      case 4:
        for(Vehicle v : arr) {
                System.out.println(v);
            }
        break;
      case 5:
        System.out.println("Name of vehicle: ");
        name = scan.next();
        char dir;
        int degree;
        for(Vehicle v : arr) {
            if(v.getName() != null && 
                    (v.getName().compareToIgnoreCase(name) == 0)) {
                System.out.print("\nDirection [R/L]: ");
                dir = scan.next().charAt(0);
                System.out.print("\nDegrees [0-360]: ");
                degree = scan.nextInt();
                if (dir == 'L') { v.turnLeft(degree); }
                if (dir == 'R') {v.turnRight(degree); }
            }
        }
        break;
      case 6:
          Car car1 = new Car("A bad car","red",100000,1999,"A111",350,0);
          Car car2 = (Car)car1.clone();
          car2.getBuyingDate().set(2003, 1, 2);
          car2.getProductionDate().set(2003, 5, 5);
          System.out.println("Date objects are separate, deep copy");
          System.out.printf("%n %tF", car1.getBuyingDate());
          System.out.printf("%n %tF %n", car2.getBuyingDate());
          System.out.printf("Production date car2 edited: "
                + "%n %tF %n", car2.getProductionDate());
          break;
      case 7:
          Car carTest = new Car("Test car","red",100000,1999,
                  "A111",350,0);
          Bicycle bicycleTest = 
                  new Bicycle("Test bicycle","red",100000,
                          1999,"A111",15,0);
          carTest.accelerate(3);
          carTest.accelerate(250);
          bicycleTest.accelerate(5);
          bicycleTest.accelerate(200);
          carTest.breaks(100);
          bicycleTest.breaks(50);
          carTest.stop();
          bicycleTest.stop();
          break;
      case 8:
        java.io.PrintWriter output = new java.io.PrintWriter(file);
        for(Vehicle v : arr) {
            v.writeData(output);
        }       
        scan.close();
        in.close();  //* **in.close() method is here**
        output.close();
        System.exit(0);
      default:
        System.out.println("Wrong input!");
      }
    }
  }
}

甚至当我投入的时候。close()在try块中,仍然显示相同的错误。

即使我把in.close()放在后面,它仍然显示同样的错误。

为什么会这样?

共有1个答案

漆雕和昶
2023-03-14

存在未关闭资源的代码路径。要么使用finally块,要么尝试使用资源。喜欢

try (Scanner in = new Scanner(file).useLocale(Locale.US)) {
    in.useDelimiter(",");
    while (in.hasNext()) {
        try {
            String vehClass = in.next();                
            Class veh1 = Class.forName(vehClass);
            Vehicle veh = (Vehicle)veh1.
                    getDeclaredConstructor().newInstance();
            arr.add(veh);
            veh.readData(in);
        } catch (Exception e) { 
            System.out.print("Exception");
            System.exit(0);
        }
    }
}
 类似资料:
  • 我收到这样的类型错误:- 甚至我正在使用jdk版本:-java版本"1.7.0_55"OpenJDK运行时环境(IcedTea 2.4.7)(7u55-2.4.7-1ubuntu1)OpenJDK 64位服务器VM(构建24.51-b03,混合模式) 请有人帮助我,我应该在我的项目中使用这样的组件。

  • 问题内容: 我正在编写一个(貌似)简单明了的SQL代码段,该代码段在确保该列存在之后将其删除。 问题:如果列不存在,代码 内 IF子句抱怨说,它无法找到列!好了, 卫生署 ,这就是为什么它的IF子句中! 所以我的问题是,为什么不应该执行的一段代码会出现错误? 这是代码段: …这是错误: 我正在使用Microsoft SQL Server 2005 Express Edition。 问题答案: IF

  • 这是我的代码: 因为我使用POM设计模式,所以我为此创建了一种方法: 这是超文本标记语言标签: 我的问题是,即使存在WebElement,isDisplayed()也返回false。

  • 公共静态无效setisInvalidDob(Boolean dob){SharedPretions首选项=PreferenceManager.getDefaultSharedPreferences(CreditMantriApplication.getCreditMantri());最终SharedPreferences.Editoredit=preferences.edit();edit.put

  • 问题内容: 现在基本设置都很好,我开始尝试事务。Struts + Spring + Hibernate注释事务管理器。这是Action中的示例代码,将调用服务类: 这是服务类中的方法: 首先,我调用了userDao,它将插入一个用户。其次,我在该服务类中调用了另一个方法。 由于PK为空,因此此操作将失败。我想第二个呼叫()将失败,但不会影响前一个。但是,未插入用户。 如果我仅致电: 它正在工作,这

  • 错误:第 1 行的解析错误:函数搜索(sour ^ 期望“字符串”、“数字”、“空”、“真”、“假”、“{”、“[”,得到“未定义” 代码: