Read files from src/main/resources in Java

Here is a sample code which reads the content of a file stored in „src/main/resources“ within a Java project.

First Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class MyFileReader {
 
  private static final Logger LOG = Logger.getLogger(MyFileReader.class.getName());
 
  // File path: src\main\resources\articles\test.md
  public static void main(String[] args) {
    String fileSeparator = System.getProperty("file.separator ", "/");
    String filePath = "articles" + fileSeparator + "test.md";
 
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream stream = classLoader.getResourceAsStream(filePath);
 
    if (stream != null) {
      LOG.log(Level.INFO, "File found: {0}", filePath);
      LOG.log(Level.INFO, "File content: {0}", readFileContent(stream));
    } else {
      LOG.log(Level.WARNING, "File could not be found: {0}", filePath);
    }
  }
 
  private static String readFileContent(InputStream stream) {
    StringBuilder sb = new StringBuilder();
    String line;
 
    // try-with-resources
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
      while ((line = reader.readLine()) != null) {
        sb.append(line);
        sb.append(System.getProperty("line.separator", "\r\n"));
      }
    } catch (IOException ex) {
      logError(ex);
    }
 
    return sb.toString();
  }
 
  private static void logError(Exception ex) {
    LOG.log(Level.WARNING, ex.getLocalizedMessage());
  }
 
}

Second Example

Using:

  • Input Stream
  • Output Stream
  • Message Template
  • String Format
  • try-with-resources Statement
package com.welovecoding.web.blog.pusher;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Main {
 
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();
    String line = "";
 
    File file = new File("src/main/resources/test.md");
 
    try (
          InputStream stream = new FileInputStream(file);
          BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))
        ) {
      while ((line = reader.readLine()) != null) {
        sb.append(line);
        sb.append(System.getProperty("line.separator", "\r\n"));
      }
    } catch (FileNotFoundException fileException) {
      LOG.log(Level.WARNING, "File cannot be found at: {0}", file.getAbsolutePath());
    } catch (IOException readException) {
      LOG.log(Level.SEVERE, "Error reading file: {0}", readException.getLocalizedMessage());
    }
 
    String formattedString = String.format("Result:\r\n%s", sb.toString());
    System.out.println(formattedString);
  }
  private static final Logger LOG = Logger.getLogger(Main.class.getName());
}

Third example

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Parser {
 
  public Parser() {
  }
 
  public void parse(String filePath) {
    if (filePath == null || filePath.isEmpty()) {
      filePath = "editorconfig-test.ini";
    }
 
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream stream = classLoader.getResourceAsStream(filePath);
    StringBuilder sb = new StringBuilder();
    String line;
 
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
      while ((line = reader.readLine()) != null) {
        sb.append(line);
        sb.append(System.getProperty("line.separator", "\r\n"));
      }
    } catch (IOException ex) {
      Logger.getLogger(Parser.class.getName()).log(Level.SEVERE, "Error reading file: {0}", ex.getMessage());
    } finally {
      System.out.println(sb.toString());
    }
  }
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.