Java: How to Read a Text File

Reading a plain text file in Java

ASCII is a TEXT file so you would use Readers for reading. Java also supports reading from a binary file using InputStreams. If the files being read are huge then you would want to use a BufferedReader on top of a FileReader to improve read performance.

Go through this article on how to use a Reader

I'd also recommend you download and read this wonderful (yet free) book called Thinking In Java

In Java 7:

new String(Files.readAllBytes(...))

(docs)
or

Files.readAllLines(...)

(docs)

In Java 8:

Files.lines(..).forEach(...)

(docs)

How to read a text file in Java Eclipse?

You are printing the Scanner object, not the File read.
To do that you have to run over the Scanner content, here is an example:

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

public class Main {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(System.getProperty("user.dir"));
File file = new File(System.getProperty("user.dir") + "/src/report.txt");
Scanner hemp = new Scanner(file);
while (hemp.hasNextLine()) {
System.out.println(hemp.nextLine());
}
}
}

If you want to read more about the Scanner functions you can see the API docs:

  • Scanner.hasNextLine()
  • Scanner.nextLine()

Reading and displaying data from a .txt file

BufferedReader in = new BufferedReader(new FileReader("<Filename>"));

Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:

String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();

How to read text files in java and access those value

It sounds like you want to read from a file? The Scanner class is very good for that.

You will have to format your text document in a different way, which means if you are programmatically writing the file, you need to split the 2 variables somehow. In my opinion, a comma (,) or a colon (:) are the easiest things to choose.

  • server_state:running
  • health_state:ok
  • heappercent:0.2 // Percentages will use floats/decimals
  • hoggingthreadcount:10
  • stuckthreadcount:1

    public void getProps() {
    String[] cur = new String[2];
    Scanner scanner = new Scanner("C:\Path/To/Your/File.txt");
    while(scanner.hasNextLine()) {
    cur = scanner.nextLine().split(":"); // a colon is simpler.
    if(cur[0].equalsIgnoreCase("server_state")) {
    server_state = cur[1];
    }
    if(cur[0].equalsIgnoreCase("health_state")) {
    health_state = cur[1];
    }
    if(cur[0].equalsIgnoreCase("heappercent")) {
    heappercent = Double.parseDouble(cur[1]);
    }
    if(cur[0].equalsIgnoreCase("hoggingthreadcount")) {
    hoggingthreadcount = Integer.parseInt(cur[1]);
    }
    if(cur[0].equalsIgnoreCase("stuckthreadcount")) {
    stuckthreadcount = Integer.parseInt(cur[1]);
    }
    }
    scanner.close();
    }

I hope this solves your problem!

Jarod.

Reading in a .txt file in Java

Here is a full running answer if you are still interested...

For input file:

 node1   node2
node1 node3
node2 node3
node3 node5
node2 node3 <<< repeating
node2 node6
node1 node3 <<< repeating

The filtered output:

 node1   node2 
node1 node3
node2 node3
node3 node5
node2 node6

SHORT ANSWER:
Use HashMap<String, String> and

check repeating nodes with
x_nodes.containsKey(x_key) && x_nodes.containsValue(x_value)

DETAILED ANSWER:
Copy & paste the following source:

public static char       q_TEXT_SEPARATOR            = '|';
public static int q_MAX_TEXT_LINE_NBR = 1000;
public static char q_ALT_ENTER = '\n';
public static String q_CUSTOM_COMMENT_CHAR = "*";
public static String q_CUSTOM_SPLIT_CHAR = " ";

public static HashMap<String, String> w_nodes = new HashMap<String, String>();



public static boolean empty_line(String input) {
boolean w_bos_bilgi = (input == null || input.equals("") || input.trim().equals(""));
return w_bos_bilgi;
}

public static String[] custom_split(String s) {
return custom_split(s, q_TEXT_SEPARATOR);
}
public static String[] custom_split(String s, char q_TEXT_SEPARATOR) {
String[] p = new String[q_MAX_TEXT_LINE_NBR];
for (int i = 0; i < q_MAX_TEXT_LINE_NBR; i++) {
p[i] = "";
}

int totlen = s.length();
int i = 0;
int k = 0;
boolean finish = false;
while (!finish) {
if ((k >= totlen) || (i >= q_MAX_TEXT_LINE_NBR)) {
finish = true;
} else {
String w_tx = "";
boolean finish2 = false;
while (!finish2) {
char c = s.charAt(k);
if (( c == q_TEXT_SEPARATOR) || (k > totlen) || (i == q_MAX_TEXT_LINE_NBR)) {
finish2 = true;
} else {
if (c != q_ALT_ENTER) {
w_tx = w_tx + c;
}
k = k + 1;
}
}
if (!empty_line(w_tx)) {
p[i] = w_tx;
i++;
}
k++;
}
}

return p;
}

public static boolean existing(HashMap<String, String> x_nodes, String x_key, String x_value) {
if ( x_nodes.containsKey(x_key) && x_nodes.containsValue(x_value) ) {return false;}
else {return true;}
}

public static void import_nodes() {
String q_NODES_FILENAME = "C://...//interactions.txt";

BufferedReader q_NODES_in = null;
try {
q_NODES_in = new BufferedReader(new FileReader(q_NODES_FILENAME));
} catch (Exception e) {
System.out.println("> WARNING : Nodes file not found !");
return;
}


String w_file_str = "", w_line = "";
while ( q_NODES_in != null && w_line != null ) {
try {
w_line = q_NODES_in.readLine();
if ( empty_line(w_line) ) {continue;}
if ( w_line.startsWith(q_CUSTOM_COMMENT_CHAR)) {continue;}

if ( w_line == null || w_line.equals("null") ) {
throw new IOException();
}

w_file_str += w_line.replace(q_TEXT_SEPARATOR + "", "") + q_TEXT_SEPARATOR;
} catch (Exception e) {
break;
}
}
try {q_NODES_in.close();} catch (Exception e) {}

if ( empty_line(w_file_str) ) {
System.out.println("> WARNING : Nodes file empty !");
return;
}


String p[] = custom_split(w_file_str);
for (int i = 0; i < p.length && !empty_line(p[i]); i++) {
String w_key = "";
String w_node = (p[i] + " ");
int w_separator = w_node.indexOf(q_CUSTOM_SPLIT_CHAR);
if ( w_separator < 0 ) {continue;}
else {w_key = w_node.substring(0, w_separator);
w_node = w_node.substring(w_separator + 1);}

if ( p[i].trim().toUpperCase().startsWith(q_CUSTOM_COMMENT_CHAR)) {continue;} //UPD 2012/10/08

if ( existing(w_nodes, w_key, w_node) ) {
w_nodes.put(w_key, w_node);
System.out.println(w_key + " " + w_node);
}
}
}

read text file in Spring boot

In spring you have to put your file in src/main/resources directory and then you can read it using @Value annotation.

class YourClass {

@Value("classpath:serviceAccountKey.json")
private Resource resource;

@PostConstruct
public void Initialization() {

try {
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(resource.getInputStream()))
.build();

FirebaseApp.initializeApp(options);
} catch (Exception e) {
System.out.println("something went wrong in firebase initialization ...");
System.out.println(e);
}

}
}



Related Topics



Leave a reply



Submit