java reads files in many ways

java reads files in many ways

This paper introduces several ways of reading files from classpath, url and jar in java.

Get ready

We use only java classes to implement a set of test examples, in which we use the Hamcrest tool for matching validation.
Test class sharing uses readFromInputStream method to transfer input stream to string, which is convenient for asserting results.

private String readFromInputStream(InputStream inputStream)
  throws IOException {
    StringBuilder resultStringBuilder = new StringBuilder();
    try (BufferedReader br
      = new BufferedReader(new InputStreamReader(inputStream))) {
        String line;
        while ((line = br.readLine()) != null) {
            resultStringBuilder.append(line).append("\n");
        }
    }
  return resultStringBuilder.toString();
}

Of course, there are other ways to achieve general functionality, you can refer to other articles in this series.

Reading files from Classpath

This section explains how to read files from Classpath, assuming that "fileTest.txt" is in the src/main/resources path:

@Test
public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() {
    String expectedData = "Hello World from fileTest.txt!!!";

    Class clazz = FileOperationsTest.class;
    InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
    String data = readFromInputStream(inputStream);

    Assert.assertThat(data, containsString(expectedData));
}

In the code snippet above, we use the getResourceAsStream method of the current class to load the file and pass the absolute path of the file as a parameter. We can also use the ClassLoader instance:

ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("fileTest.txt");
String data = readFromInputStream(inputStream);

We take the current class classLoader and use the getClass().getClassLoader() method. The difference between the two is that the getResourceAsStream method is used on the ClassLoader instance, and the path represents the absolute path of the classpath. With class instances, the path is absolute relative to the package or indicated at the beginning of the backslash.

Read files using jdk7

NIO packages in jdk7 have been greatly improved. Let's look at an example using the Files class and readAllBetes method. The readAllBetes method receives the Path parameter, and the Path class is considered an upgrade to java.io.File with additional operations:

@Test
public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() {
   String expectedData = "Hello World from fileTest.txt!!!";

   Path path = Paths.get(getClass().getClassLoader()
     .getResource("fileTest.txt").toURI());       
   byte[] fileBytes = Files.readAllBytes(path);
   String data = new String(fileBytes);

   Assert.assertEquals(expectedData, data.trim());
}

jdk8 read file

The lines() method of the Files class in jdk8 can get the string stream. The following example reads the file value bytes, and then uses utf-8 encoding to generate characters.

@Test
public void givenFilePath_whenUsingFilesLines_thenFileData() {
    String expectedData = "Hello World from fileTest.txt!!!";

    Path path = Paths.get(getClass().getClassLoader()
      .getResource("fileTest.txt").toURI());

    StringBuilder data = new StringBuilder();
    Stream<String> lines = Files.lines(path);
    lines.forEach(line -> data.append(line).append("\n"));
    lines.close();

    Assert.assertEquals(expectedData, data.toString().trim());
}

With Stream on the io channel, such as file operations, we need to close the stream with close() display.

Read files using FileUtils

Another common approach is to use the FileUtils class, which requires additional dependencies:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

The latest version can be applied.

@Test
public void givenFileName_whenUsingFileUtils_thenFileData() {
    String expectedData = "Hello World from fileTest.txt!!!";

    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("fileTest.txt").getFile());
    String data = FileUtils.readFileToString(file);

    Assert.assertEquals(expectedData, data.trim());
}

We pass the File object to the method readFileToString() of the FileUtils class. This tool class is responsible for loading content, creating InputStream instances and reading data without writing any template code.

Read data from url

Read from the url. In the example, we use "/" as the url:

@Test
public void givenURLName_whenUsingURL_thenFileData() {
    String expectedData = "Baeldung";

    URL urlObject = new URL("/");
    URLConnection urlConnection = urlObject.openConnection();
    InputStream inputStream = urlConnection.getInputStream();
    String data = readFromInputStream(inputStream);

    Assert.assertThat(data, containsString(expectedData));
}

In addition to using standard sdk URLs and URLConnection classes, there are other ways to achieve this.

Read files from jar

To read the contents of a file from a local jar file, you need to have a file in the jar. In the example, we read the "LICENSE.txt" file in "hamcrest-library-1.3.jar":

@Test
public void givenFileName_whenUsingJarFile_thenFileData() {
    String expectedData = "BSD License";

    Class clazz = Matchers.class;
    InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
    String data = readFromInputStream(inputStream);

    Assert.assertThat(data, containsString(expectedData));
}

Here we load the LICENSE.txt file in the Hamcrest library, so we use Matcher to get resource s. ClassLoader can also be used to load.

summary

This article describes how to read files, classpath s, URL s, and jar s from different locations, and uses the java core api to demonstrate how to get content from files.

Keywords: Java encoding SDK

Added by dynamicallystatic on Sat, 18 May 2019 15:34:19 +0300