当前位置: 首页 > 知识库问答 >
问题:

在Java中读取. txt文件

赖鸿羲
2023-03-14

我正试图编写一个程序,读取网络中相互交互的节点列表。它以以下格式写入文本文件:

node1   node2
node1   node3
node2   node3
node3   node5

这表示节点1与节点2和节点3交互,节点2仅与节点3交互,等等。

该程序将能够读取该文件,并将删除任何重复的交互,并且如果我输入节点的名称,将能够向我返回节点与其他节点的交互次数。然而,我对Java非常陌生,我首先尝试让它读入文件,尽管我的代码目前没有读入文件。以下是我迄今为止的代码:

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

任何关于如何解决此问题的帮助都将不胜感激,谢谢!

共有3个答案

池照
2023-03-14

这是一个完整的运行答案,如果您仍然感兴趣。。。

对于输入文件

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

过滤后的输出:

 node1   node2 
 node1   node3 
 node2   node3 
 node3   node5 
 node2   node6 

简单回答:使用HashMap

使用x_nodes.containsKey(x_key)检查重复节点

详细答案:复制

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);
       }
   }
}
公孙芷阳
2023-03-14

只是一个如何为任务封装代码的小例子。请原谅我的语法,我希望你能阅读它。

// extends means that the class will inherit properties of HashMap
// Parameters between <> are generics, they determinate the types
// that are used as keys and values and same goes for HashSet, It does not matter
// what you substitute here as long as its not a buildin type (so not int but 
// Integer), if you dont know what hashmap is or dont understand generics, search 
// it on internet
public class Network extends HashMap<String, HashSet<String>> {
        // this is a constructor as it is named the same as Class and hes not 
        // return type specified. in this case we are initializin contents of the 
        // map and throws specifies that this Method can fail and what it can   
        // throw, this is java vay of passing errors up and leaving caller to 
        // handle then.
        public Network(String filename) throws IOException {
                // This is what i hate about java and that are buffer readers
                // this isnt that bad but if you get like 4 nested to each other...
                BufferedReader reader = new BufferedReader(new FileReader(filename));
                
                while(true) {
                    String line = reader.readLine();
                    if(line == null) return; // null signalizes we read all lines
                    // look for dosc of String.split if you dont know what it 
                    // does
                    String[] nds = line.split(" ");
                    // as you can see we can call methods of Hashmap, like 
                    // computeIfAbsent, as if it was member of Network. That 
                    // wierd arrow is an lambda expression, search for java lambda 
                    // expressions to learn more, same goes for computeIfAbsent
                    HashSet<String> set = computeIfAbsent(nds[0], k -> new HashSet<>());
                    // Finally as ewerithing in java is pointer except some 
                    // simple types we can modify set like so. Good thing about 
                    // set is that i takes care of ensuring that we have no 
                    // duplicates 
                    set.add(nds[1]);
                }
        }

        // a simple abstraction that encapsulates logic, as i dont like returning 
        // null in this case, throwing an exception makes it more obvious, though
        // of corse you might change it for better user experiance as writing try
        // catchs ewriwhare is annoying
        public int getInteractionCountFor(String nodeName) throws NoSuchElementException {
            HashSet<String> set = get(nodeName);
            if (set == null) {
                // throwing our own exception with custom message
                throw new NoSuchElementException("the network does not contain " + nodeName);
            }
            return  set.size();
        }
    }
傅自明
2023-03-14

这可能是因为您正在查找的位置不存在文件。您可能错过了catch子句,在那里可以打印确切的异常。

首先,尝试运行这个:

public static void main(String[] args) throws IOException {
    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();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

文件应该在项目的根级别,这也可能对您有所帮助

public static void main(String[] args) throws IOException {
    try {
        File myObj = new File("interactions.txt");

        // check if file exists - if not - create
        if (myObj.createNewFile()) {
            System.out.println("File created: " + myObj.getName());
        } else {
            System.out.println("File already exists.");
        }
        Scanner FileReader = new Scanner(myObj);
        while (FileReader.hasNextLine()) {
            String data = FileReader.nextLine();
            System.out.println(data);
        }
        FileReader.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}
 类似资料:
  • 问题内容: 我会尽量保持清楚,但如果我的问题不完美,请原谅我。我有一个包含多行数据的txt文件。例: 123拉尔夫·玻色20000 200 1 2 256 ed shane 30000 100 2 4 … 我需要按顺序读取每一行,并将其传递回单独类中的方法进行处理。我知道如何通过使用StringTokenizer将每一行分解为元素。 但是,我不确定如何一次读取一行,将元素传递回另一类,然后在完成处

  • 我的项目中有这样一段代码: 没有错误,应用程序运行正常,但是变量中从来没有任何文本,我确信txt文件中有文本! 我已经尝试过不同的方法来读取文本文件(使用BufferedReader、Scanner、FileInputStream和FileReader),但都不起作用。 另外,我几乎可以肯定问题不在变量中,因为我尝试通过代码(使用运行时)打开文件,它正常打开了正确的文件。 好的,我尝试添加,但是仍

  • 我正在编写一个程序,使用一个文件中的30个分数,计算出最低、最高和平均分数。我很难理解如何编写循环语句来读取每个等级并更新最低/最高等级,并在读取下一个等级之前将该值添加到总和。 谢谢想出来了:

  • 问题内容: 比方说,我有一个文件夹,名为和里面我有,和。如何使用Java和读取文件夹中的所有文件(如果可能的话)? 问题答案: 类似于以下内容应该可以帮助您,请注意,为了简单起见,我使用apache commons FileUtils而不是弄乱缓冲区和流…

  • 问题内容: 请看下面的代码 在这里,首先获取文件的字节,然后将其写入文本文件。然后,我阅读了该文本文件,逐行阅读,并为每一行生成了一个单独的.txt文件。现在,原始程序被拆分为数千个文件。现在,我需要阅读所有.txt文件并重新生成.txt文件。我不知道怎么做最后一件事。我怎样才能做到这一点?请帮忙! 问题答案: 如果要操作任何类型的文件,请不要认为它们包含文本数据,而应将它们视为包含字节的二进制文

  • 问题内容: 我正在研究一个Java程序,该程序逐行读取文本文件,每个文本文件都有一个数字,将每个数字都将其扔到数组中,然后尝试使用插入排序对数组进行排序。我需要有关程序读取文本文件的帮助。 我收到以下错误消息: 我的“ src”,“ bin”和主项目文件夹中有.txt文件的副本,但仍找不到该文件。我正在使用Eclipse。 问题答案: 你必须把文件扩展名放在这里