Reading in a .txt file in Java

Tags: ,



I am trying to write a program which reads in a a list of nodes that interact with each other within a network. This is written in a text file in the format:

node1   node2
node1   node3
node2   node3
node3   node5

This indicates node1 interacts with node2 and node3, node 2 interacts with only node3 etc.

The program will be able to read in this file and will remove any repeated interactions and will be able to return to me the number of interactions a node has with other nodes if I input the name of the node. However, I am very new to Java and am first trying to get it to read in the file, although my code does not read in the file at the moment. Here is the code I have so far:

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

public class ReadFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("interactions.txt");
      Scanner FileReader = new Scanner(myObj);
      while (FileReader.hasNextLine()) {
        String data = FileReader.nextLine();
        System.out.println(data);
      }
      FileReader.close();
    } 
  }
}

Any help on how to solve this would be really appreciated, thank you!

Answer

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);
       }
   }
}


Source: stackoverflow