简体   繁体   English

Java的类常量和文件导入

[英]class constants and file imports for java

I'm pretty much trying to use a class constant to declare as a file but get an error. 我几乎在尝试使用类常量声明为文件,但出现错误。

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

public class BabyNames {
   public static final Scanner NAME=new Scanner(new File("names.txt")); //specifically this part 
   public static final int YEAR=1900;                                   //generates the error
   public static final int LS=11;
   public static final int WIDTH=50;
   public static void main(String[] args) throws FileNotFoundException{
      intro();
      personName();
      graph();
   }

// Error contained:
// BabyNames.java:6: error: unreported exception FileNotFoundException; must be caught or
// declared to be thrown                 
//   public static final Scanner NAME=new Scanner(new File("names.txt"));
                                ^
//1 error

this is not all of the program but dont think the rest is required. 这不是全部程序,但不要认为其余部分是必需的。 sorry if my method of asking was funky, first time. 抱歉,第一次问我的方法是否时髦。 thanks much. 非常感谢。

You need a try catch around that code. 您需要尝试了解该代码。

That's what "must be caught or declared to be thrown" means. 这就是“必须被抓住或宣布要扔”的意思。

Read this : doc oracle 阅读本文: doc oracle

There are two types of Exception : 1) checked Exception: those should be handle at compile time (by using try,catch,throws) 2) unchecked Exception: No compiler error for these exception but at run time exception may occurs. 异常有两种类型:1)已检查的异常:应在编译时处理(通过使用try,catch,throws处理)2)未检查的异常:这些异常不会在编译器中出错,但在运行时可能会发生异常。

Your case is first one FileNotFoundException is checked exception so either you have to write that line inside try catch block or you have to use keyword throws. 您的情况是第一个FileNotFoundException被检查异常,因此您必须在try catch块中写入该行,或者必须使用关键字throws。 to pass exception handling to calling method. 将异常处理传递给调用方法。

Technically you can use a static initializer block to set your staic final Scanner variable. 从技术上讲,您可以使用静态初始化程序块来设置静态的最终Scanner变量。 Inside the initializer block you can use try/catch: 在初始化程序块内,您可以使用try / catch:

public static final Scanner NAME; 

static {
  // Be sure scanner is initialized even in the case of an exception
  Scanner scanner = null;

  try {
    new Scanner(new File("names.txt"));
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  }
  NAME = scanner;
}

BUT: It is bad style to hold an instance of a class like Scanner as a static constant. 但是:将诸如Scanner类的类的实例作为静态常量保存是不好的样式。 A Scanner is a one way object. 扫描仪是一种单向对象。 You are about to consume the file content and that's it. 您将要消耗文件内容,仅此而已。 It doesn't make sense to hold such an object as a constant and much less if it is public . 将这样的对象保持为常量是没有意义的,如果它是public少得多。 A static variable will be intialized as soon as the class is loaded and lives as long as your program. 静态变量将在类加载后立即初始化,并且与您的程序一样有效。 In most cases this is not what you want. 在大多数情况下,这不是您想要的。

A better approach would be to make it an instance variable and initilize it in the constructor. 更好的方法是使其成为实例变量,并在构造函数中对其进行初始化。 And make it private to the class. 并将其私有化。 You can hold the file name as a constant and create the constructor to accept any file name. 您可以将文件名作为常量保存,并创建构造函数以接受任何文件名。 The methods intro() , personName() and graph() can be made instance methods, too. 方法intro()personName()graph()也可以成为实例方法。

public class BabyNames {
  public static final String NAMES_FILE_NAME = "names.txt";

  public static final int YEAR=1900;                                   
  public static final int LS=11;
  public static final int WIDTH=50;

  private final Scanner name; 

  public BabyNames(String fileName) throws FileNotFoundException {
    name = new Scanner(new File(fileName));

  }

  public static void main(String[] args) throws FileNotFoundException {
    BabyNames babyNames = new BabyNames(NAMES_FILE_NAME);
    babyNames.intro();
    babyNames.personName();
    babyNames.graph();
  }

  public void graph() {
    // ...    
  }

  public void personName() {
    // ...    
  }

  public void intro() {
    // ...    
  }

  // ...
}

As a consequence the Scanner variable is only known to the BabyNames class and lives as long as the particular BabyNames instance. 因此,Scanner变量仅对于BabyNames类是已知的,并且只要特定的BabyNames实例有效即可。 This is more modular, better to maintain and easier to test. 这更加模块化,易于维护且易于测试。 Eg you can write a unit test and initialize your class with a test file. 例如,您可以编写单元测试,并使用测试文件初始化类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM