Sunday, 12 January 2020

Java read file content as string in one line


Below snippet read file content as string.
new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

App.java

package com.sample.app;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class App {

 public static String readFileAsString(String filePath) throws IOException {
  if (filePath == null || filePath.isEmpty()) {
   return null;
  }

  return new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
 }

 public static void main(String args[]) throws IOException {
  String filePath = "logfile.txt";
  String data = readFileAsString(filePath);
  System.out.println(data);
 }

}


You may like

No comments:

Post a Comment