2017-04-09 77 views
-3

我不知道为什么它采取负面投票。我不想把我的代码给大家使用。和即时通讯不要求代码即时通讯要求逻辑,所以我可以做到这一点从文件中读取条件java

我写这个Java代码,我想条件从文件中读取。 有可能吗?如果你有任何教程。或任何能够帮助我理解如何去做的事情。 我只是想了解更多的逻辑。

我已经尝试把每个条件放在一个文件中,并阅读表格。

if(con == 1){ 
     Scanner myScanner = new Scanner(new File("con.txt")); 
    } 
    else if(con == 2){ 
     Scanner myScanner = new Scanner(new File("con2.txt")); 
    } 
    else if(con == 3){ 
     Scanner myScanner = new Scanner(new File("con3.txt")); 
    } 
    else{ 
     System.out.println("You did not choose one of the 3 con"); 
    } 

但它没有工作,因为在每个if语句中有2种情况需要被满足。

我希望这是有道理的

+1

欢迎来到Stack Overflow!请[参观](http://stackoverflow.com/tour)了解网站的工作原理以及在这里的主题。另请参阅:[为什么“有人可以帮我吗?”不是一个真正的问题?](http://meta.stackoverflow.com/q/284236) –

+0

2条件是什么? –

回答

0

所以我真的不能看到这里的条件下,只有一个选择的1,2或3。如果是这样的话,那么你最好使用一个开关,然后使用你的别人作为默认情况。


因此,从属性文件中读取以防万一需要加载属性。下面是一个例子。

首先创建一个名为“configuration.properties”的文件,并为此示例放置以下内容;

  • property1 = myPropertyOne
  • property2 = myPropertyTwo
  • property3 = myPropertyThree

现在下面是读取属性文件,将它们放置成Java Properties Object一个例子,然后最终将它们打印出来。

Properties myProperties = new Properties(); 
InputStream fileInput = null; // Here so you can close it in the finally section 

try { 
    fileInput = new FileInputStream("configuration.properties"); 
    myProperties.load(fileInput); // pass the input stream into properties to be read 

    // print out all the properties values for given keys 
    System.out.println(myProperties.getProperty("property1")); 
    System.out.println(myProperties.getProperty("property2")); 
    System.out.println(myProperties.getProperty("property3")); 

} catch (IOException exceptionThrown) { 
     // would be best to handle the exception here 
} finally { 
    if (fileInput != null) { 
     try { 
      fileInput.close(); 
     } catch (IOException e) { 
      // handle exception for attempting to close handler 
     } 
    } 
}