In this article we are going to see about how to read file from class path or from resource folder.
Content in javatutorialcorner.txt
FileLoader.java
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
Content in javatutorialcorner.txt
SpringUsing ClassLoader(), all paths are "absolute" (there's no context), from which they could be relative. Therefore you don't need a leading slash.
Hibernate
Core Java
Java 8
Java 7
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
0 comments:
Post a Comment