java 读取集合文件属性_如何在Java中读取属性文件

java 读取集合文件属性

Most of the time you need to read configurations properties from the files, for example, you don’t want to put database names, passwords in the code directly. Not only database properties, but there are also so many reasons such as reading properties according to the language, etc. In this post, we will see how we can read the properties file in Java.

大多数时候,您需要从文件中读取配置属性,例如,您不想直接在代码中放入数据库名称和密码。 不仅是数据库属性,还有很多原因,例如根据语言读取属性等。在本文中,我们将看到如何读取Java中的属性文件。

  • Prerequisites

    先决条件

  • Example Project

    示例项目

  • Implementation

    实作

  • Summary

    概要

  • Conclusion

    结论

先决条件(Prerequisites)

There are some prerequisites for this project such as Apache Maven, Java SDK, and some IDE. You need to install all these on your machine if you want to run this example project on your machine.

此项目有一些先决条件,例如Apache Maven,Java SDK和某些IDE。 如果要在计算机上运行此示例项目,则需要在计算机上安装所有这些工具。

Once you install all of the above you can check the version of both maven and java with the following command

安装完上述所有内容后,您可以使用以下命令检查maven和java的版本

java --version
mvn --version

Let’s generate the basic Maven project with the following command.

让我们使用以下命令生成基本的Maven项目。

mvn archetype:generate -DgroupId=com.bachinalabs.fileread \
-DartifactId=App \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DarchetypeVersion=1.4 \
-DinteractiveMode=false

You can load the generated project with the IntelliJ IDEA. You can use any other IDE such as eclipse, etc.

您可以使用IntelliJ IDEA加载生成的项目。 您可以使用其他任何IDE,例如eclipse等。

Image for post

示例项目 (Example Project)

Here is the example project where you can clone the project from the GitHub and run it on your machine with the following commands.

这是示例项目,您可以在其中从GitHub克隆项目,并使用以下命令在计算机上运行它。

// clone the project
git clone https://github.com/bbachi/file-read-java.git

You can this project with the following commands.

您可以使用以下命令进行该项目。

实作 (Implementation)

There are three ways we can implement reading files in Java projects we will see all of the methods. Let’s define the file called application.properties under the folder src/main/resources.

我们可以通过三种方法在Java项目中实现读取文件,我们将看到所有方法。 让我们在文件夹src / main / resources下定义一个名为application.properties的文件。

来自类路径的InputStream (InputStream From Classpath)

According to the Oracle Docs Here, A system resource is a resource that is either built-in to the system or kept by the host implementation in, for example, a local file system. Programs access system resources through the ClassLoader methods getSystemResource and getSystemResourceAsStream.

根据此处的Oracle Docs ,系统资源是系统内置的资源或主机实现保存在例如本地文件系统中的资源。 程序通过ClassLoader方法getSystemResourcegetSystemResourceAsStream访问系统资源。

For example, in a particular implementation, locating a system resource may involve searching the entries in the CLASSPATH. The ClassLoader methods search each directory, ZIP file, or JAR file entry in the CLASSPATH for the resource file, and, if found, returns either an InputStreamor the resource name. If not found, the methods return null. A resource may be found in a different entry in the CLASSPATH than the location where the class file was loaded.

例如,在特定实现中,定位系统资源可能涉及搜索CLASSPATH中的条目。 ClassLoader方法在CLASSPATH中的每个目录,ZIP文件或JAR文件条目中搜索资源文件,如果找到,则返回InputStream或资源名称。 如果未找到,则这些方法返回null。 可以在CLASSPATH的其他条目中找到与加载类文件的位置不同的资源。

First, we need to define the properties file as shown below under /src/main/resources.

首先,我们需要定义属性文件,如下所示在/ src / main / resources下。

message.one=This is first message
message.two=This is second message
message.three=This is third message
message.four=This is fourth message
message.five=This is fifth message
message.six=This is sixth message
message.seven=This is seventh message
message.eight=This is eighth message
message.nine=This is ninth message
message.ten=This is tenth message

Let’s define the class called ApplicationProperties and load this properties file with the ClassLoader and getResourceAsStream. This method throws the exception called IOEception if the file is not found. Since we are loading this file in the constructor properties file is loaded in the Properties variable.

让我们定义一个名为ApplicationProperties的类,并使用ClassLoader和getResourceAsStream加载此属性文件。 如果找不到该文件,则此方法将引发称为IOEception的异常。 由于我们正在构造器中加载此文件,因此属性文件中将加载属性文件。

package com.bachinalabs.fileread;


import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;


public class ApplicationProperties {


    private final Properties properties;


    ApplicationProperties() {
        properties = new Properties();
        try {
            properties.load(getClass().getClassLoader().getResourceAsStream("application.properties"));


        } catch (IOException ioex) {
            Logger.getLogger(getClass().getName()).log(Level.ALL, "IOException Occured while loading properties file::::" +ioex.getMessage());
        }
    }


    public String readProperty(String keyName) {
        Logger.getLogger(getClass().getName()).log(Level.INFO, "Reading Property " + keyName);
        return properties.getProperty(keyName, "There is no key in the properties file");
    }


}

Lets’s test with the following main class.

让我们用以下主要类进行测试。

package com.bachinalabs.fileread;


import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * ReadMain
 *
 */
public class ReadMain
{
    public static void main( String[] args )
    {
        ApplicationProperties properties = new ApplicationProperties();


        Logger.getLogger("App Main").log(Level.INFO, properties.readProperty("message.one"));
        Logger.getLogger("App Main").log(Level.INFO, properties.readProperty("message.two"));
        Logger.getLogger("App Main").log(Level.INFO, properties.readProperty("message.three"));
        Logger.getLogger("App Main").log(Level.INFO, properties.readProperty("message.four"));
        Logger.getLogger("App Main").log(Level.INFO, properties.readProperty("message.no.property"));


    }
}

Here is the output when you run the above class

这是运行上述类时的输出

Image for post
Output 输出量

FileInputStream(FileInputStream)

According to the Oracle docs here, A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.

根据此处的Oracle文档FileInputStream从文件系统中的文件获取输入字节。 可用的文件取决于主机环境。

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

FileInputStream用于读取原始字节流,例如图像数据。 要读取字符流,请考虑使用FileReader

First, we need to define the properties file called file.properties as shown below under src/main/files.

首先,我们需要定义名为file.properties的属性文件,如下所示在src / main / files下。

file.name=some-file-name
file.extension=.pdf

Let’s define the class called FileProperties and load this properties file with the FileInputStream. This method throws the exception called FileNotFoundException if the file is not found. Since we are loading this file in the constructor properties file is loaded in the Properties variable.

让我们定义一个名为FileProperties的类,并使用FileInputStream加载此属性文件。 如果找不到文件,此方法将引发名为FileNotFoundException的异常。 由于我们正在构造器中加载此文件,因此属性文件中将加载属性文件。

package com.bachinalabs.fileread;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;


public class FileProperties {


    private final Properties properties;


    FileProperties() {
        properties = new Properties();
        try {
            properties.load(new FileInputStream("src/main/files/file.properties"));


        } catch (FileNotFoundException ex) {
            Logger.getLogger(getClass().getName()).log(Level.ALL, "FileNotFoundException Occured while loading properties file::::" +ex.getMessage());
        } catch (IOException ioex) {
            Logger.getLogger(getClass().getName()).log(Level.ALL, "IOException Occured while loading properties file::::" +ioex.getMessage());
        }
    }


    public String readProperty(String keyName) {
        Logger.getLogger(getClass().getName()).log(Level.INFO, "Reading Property " + keyName);
        return properties.getProperty(keyName, "There is no key in the properties file");
    }
}

Lets’s test with the following main class.

让我们用以下主要类进行测试。

package com.bachinalabs.fileread;


import java.util.logging.Level;
import java.util.logging.Logger;


public class ReadWithFileInputStream {


    public static void main( String[] args )
    {
        FileProperties properties = new FileProperties();


        Logger.getLogger("ReadWithFileInputStream").log(Level.INFO, properties.readProperty("file.name"));
        Logger.getLogger("ReadWithFileInputStream").log(Level.INFO, properties.readProperty("file.extension"));
        Logger.getLogger("ReadWithFileInputStream").log(Level.INFO, properties.readProperty("message.no.property"));


    }
}

Here is the output when you run the above class.

这是运行上述类时的输出。

Image for post
output 输出

文件阅读器(FileReader)

FileReader is meant for reading streams of characters. First, we need to define the properties file called db.properties as shown below under src/main/db.

FileReader用于读取字符流。 首先,我们需要定义名为db.properties的属性文件,如下所示在src / main / db下。

database.name=some-database
database.driver=some-driver
database.username=user-name
database.password=password

Let’s define the class called DBProperties and load this properties file with the FileReader. This method throws the exception called FileNotFoundException if the file is not found. Since we are loading this file in the constructor properties file is loaded in the Properties variable.

让我们定义一个称为DBProperties的类,并使用FileReader加载此属性文件。 如果找不到文件,此方法将引发名为FileNotFoundException的异常。 由于我们正在构造器中加载此文件,因此属性文件中将加载属性文件。

package com.bachinalabs.fileread;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;


public class DBProperties {


    private final Properties properties;


    DBProperties() {
        properties = new Properties();
        try {
            properties.load(new FileReader("src/main/db/db.properties"));


        } catch (FileNotFoundException ex) {
            Logger.getLogger(getClass().getName()).log(Level.ALL, "FileNotFoundException Occured while loading properties file::::" +ex.getMessage());
        } catch (IOException ioex) {
            Logger.getLogger(getClass().getName()).log(Level.ALL, "IOException Occured while loading properties file::::" +ioex.getMessage());
        }
    }


    public String readProperty(String keyName) {
        Logger.getLogger(getClass().getName()).log(Level.INFO, "Reading Property " + keyName);
        return properties.getProperty(keyName, "There is no key in the properties file");
    }
}

Lets’s test with the following main class.

让我们用以下主要类进行测试。

package com.bachinalabs.fileread;


import java.util.logging.Level;
import java.util.logging.Logger;


public class ReadWithFileReader {


    public static void main( String[] args )
    {
        DBProperties properties = new DBProperties();


        Logger.getLogger("ReadWithFileReader").log(Level.INFO, properties.readProperty("database.name"));
        Logger.getLogger("ReadWithFileReader").log(Level.INFO, properties.readProperty("database.driver"));
        Logger.getLogger("ReadWithFileReader").log(Level.INFO, properties.readProperty("message.no.property"));


    }
}

Here is the output when you run the above class.

这是运行上述类时的输出。

Image for post
output 输出

概要(Summary)

  • Most of the time you need to read configurations properties from the files, for example, you don’t want to put database names, passwords in the code directly.

    大多数时候,您需要从文件中读取配置属性,例如,您不想直接在代码中放入数据库名称和密码。
  • There are three different ways to read files in Java such as ClassLoader, FileInputStream, and FileReader.

    有三种不同的Java读取方法,例如ClassLoader,FileInputStream和FileReader。
  • FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

    FileInputStream用于读取原始字节流,例如图像数据。 要读取字符流,请考虑使用FileReader

  • This FileinputStream and FileReader throw the exception called FileNotFoundException if the file is not found.

    如果找不到该文件,则此FileinputStream和FileReader引发名为FileNotFoundException的异常

  • Properties.load() throws IOException.

    Properties.load()引发IOException。
  • These should be handled with the try-catch blocks.

    这些应使用try-catch块进行处理。

结论 (Conclusion)

There are three different ways you can choose any method based on your need.

您可以根据需要选择三种方法来选择任何一种方法。

翻译自: https://medium.com/bb-tutorials-and-thoughts/how-to-read-properties-file-in-java-6651fe2c6cbf

java 读取集合文件属性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java,要读取一个txt文件的内容并将其输出至集合,可以按照以下步骤完成。 首先,我们需要使用Java文件读取机制来读取txt文件。可以使用Java的FileReader和BufferedReader类来实现。我们需要先将txt文件转换为File对象,然后将其传递给FileReader类进行读取,并使用BufferedReader类对读取的内容进行缓存。 然后,我们需要创建一个集合对象,用于存储读取到的内容。可以选择ArrayList或LinkedList等集合类来存储数据。 在代码,我们定义一个ArrayList对象来存储每一行的内容。 接下来,在while循环,我们可以使用readLine()方法逐行读取txt文件的内容,并将其添加至集合,直到文件的内容全部被读取完毕。在readLine()方法返回null时,表示已经读取文件的末尾。 最后,我们可以遍历集合的元素,并进行输出。可以使用for-each循环或者get()方法配合循环索引来完成。在输出之前,可以根据需要对读取到的内容进行进一步的处理,如打印、存储到变量等。 总结起来,读取txt文件内容并输出至集合的过程如下: 1. 创建FileReader和BufferedReader对象,通过File对象来读取txt文件。 2. 创建一个ArrayList对象,用于存储读取到的每一行内容。 3. 使用while循环和readLine()方法逐行读取txt文件内容,并将其添加至集合。 4. 遍历集合的元素,并进行输出或其他处理。 请注意,这只是一个简单的示例,实际操作还需要注意对文件的异常处理、编码格式的匹配等问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值