We are moved to new domain
Click -> www.ehowtonow.com
Tuesday, 8 August 2017

Read File From Class Path or Resource Folder

In this article we are going to see about how to read file from class path or from resource folder.
Content in javatutorialcorner.txt
Spring
Hibernate
Core Java
Java 8
Java 7
Using ClassLoader(), all paths are "absolute" (there's no context), from which they could be relative. Therefore you don't need a leading slash.
FileLoader.java
package com.test;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class FileLoader {

 public static void main(String[] args) {
  FileLoader fileLoader = new FileLoader();
  fileLoader.readFile();
 }

 public void readFile() {

  StringBuilder sb = new StringBuilder("");

  ClassLoader classLoader = getClass().getClassLoader();
  File file = new File(classLoader.getResource("javatutorialcorner.txt")
    .getFile());

  try (Scanner scanner = new Scanner(file)) {

   while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    sb.append(line).append("\n");
   }

   scanner.close();

  } catch (IOException e) {
   e.printStackTrace();
  }

  System.out.println(sb.toString());

 }
}
Output :
Spring
Hibernate
Core Java
Java 8
Java 7

Here we see the same example without ClassLoader()
From Class, the path is relative to the package of the class .We have to include a leading slash to read the file path.
FileLoader.java
package com.test;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class FileLoader {

 public static void main(String[] args) {
  FileLoader fileLoader = new FileLoader();
  fileLoader.readFile();
 }

 public void readFile() {

  StringBuilder sb = new StringBuilder("");

  File file = new File(getClass().getResource("/javatutorialcorner.txt")
    .getFile());

  try (Scanner scanner = new Scanner(file)) {

   while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    sb.append(line).append("\n");
   }

   scanner.close();

  } catch (IOException e) {
   e.printStackTrace();
  }

  System.out.println(sb.toString());

 }
}

Output
Spring
Hibernate
Core Java
Java 8
Java 7


Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: Read File From Class Path or Resource Folder Rating: 5 Reviewed By: eHowToNow