Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中读取.txt文件_Java_File - Fatal编程技术网

在Java中读取.txt文件

在Java中读取.txt文件,java,file,Java,File,我正试图编写一个程序,读取网络中相互作用的节点列表。它以以下格式写入文本文件: node1 node2 node1 node3 node2 node3 node3 node5 这表示节点1与节点2和节点3交互,节点2仅与节点3交互等 如果我输入节点的名称,程序将能够读取该文件并删除任何重复的交互,并且能够向我返回一个节点与其他节点的交互次数。然而,我对Java非常陌生,我首先尝试在文件中读取它,尽管我的代码目前没有在文件中读取。以下是我目前掌握的代码: import java.

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

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

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

这可能是因为您正在查找的位置不存在文件。 您可能错过了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();
    }
}

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

//extends表示该类将继承HashMap的属性
//参数之间是泛型,它们决定了类型
//它们被用作键和值,HashSet也是如此,这并不重要
//只要不是构建类型(所以不是int而是
//整数),如果您不知道hashmap是什么或不理解泛型,请搜索
//它在互联网上
公共类网络扩展HashMap{
//这是一个构造函数,因为它的名称与类相同,而不是
//指定的返回类型。在本例中,我们在
//map和throws指定此方法可能失败以及它可能失败的原因
//抛出,这是传递错误并将调用方留给
//那就处理吧。
公共网络(字符串文件名)引发IOException{
//这就是我讨厌java和缓冲区读取器的地方
//这并不是很糟糕,但是如果你有4个嵌套在一起。。。
BufferedReader reader=新的BufferedReader(新文件读取器(文件名));
while(true){
字符串行=reader.readLine();
if(line==null)return;//null表示我们读取所有行
//如果不知道是什么,请查找String.split的dosc
//做
字符串[]nds=行。拆分(“”);
//如您所见,我们可以调用Hashmap的方法,如
//计算机被发送了,就好像它是网络的一员
//wierd arrow是一个lambda表达式,搜索java lambda
//表达式要了解更多信息,ComputeFabSent也是如此
HashSet set=computeIfAbsent(nds[0],k->newhashset());
//最后,java中的eWriting是指针,除了一些
//简单的类型我们可以这样修改集合。关于
//我负责确保我们没有
//复制品
set.add(nds[1]);
}
}
//一个封装逻辑的简单抽象,因为我不喜欢返回
//在本例中为null,但抛出异常会使其更加明显
//当然,您可以在编写时更改它以获得更好的用户体验
//什么是讨厌的
public int getInteractionCountFor(字符串nodeName)抛出NoTouchElementException{
HashSet=get(nodeName);
if(set==null){
//使用自定义消息引发我们自己的异常
抛出新的NoSuchElementException(“网络不包含”+nodeName);
}
返回set.size();
}
}

如果您仍然感兴趣,这里有一个完整的答案

对于输入文件:

 node1   node2
 node1   node3
 node2   node3
 node3   node5
 node2   node3 <<< repeating
 node2   node6
 node1   node3 <<< repeating
简短回答: 使用HashMap和

使用检查重复节点 x_节点。containsKey(x_键)和&x_节点。containsValue(x_值)

详细答案: 复制并粘贴以下源:

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);
       }
   }
}
publicstaticcharq_TEXT_分隔符='|';
公共静态整数q_MAX_TEXT_LINE_NBR=1000;
公共静态字符q_ALT_ENTER='\n';
公共静态字符串q_CUSTOM_COMMENT_CHAR=“*”;
公共静态字符串q_CUSTOM_SPLIT_CHAR=“”;
public static HashMap w_nodes=new HashMap();
公共静态布尔空_行(字符串输入){
布尔值w|u bos|bilgi=(输入==null | |输入.equals(“”)| |输入.trim().equals(“”);
返回w_bos_bilgi;
}
公共静态字符串[]自定义_拆分(字符串s){
返回自定义分割(s、q、文本分隔符);
}
公共静态字符串[]自定义拆分(字符串s,字符q\u文本分隔符){
字符串[]p=新字符串[q_MAX_TEXT_LINE_NBR];
对于(int i=0;i=totlen)| |(i>=q_MAX_TEXT_LINE_NBR)){
完成=真;
}否则{
字符串w_tx=“”;
布尔finish2=false;
而(!finish2){
char c=s.charAt(k);
if((c==q_TEXT_SEPARATOR)| |(k>totlen)| |(i==q_MAX_TEXT_LINE_NBR)){
finish2=真;
}否则{
如果(c!=q_ALT_ENTER){
w_tx=w_tx+c;
}
k=k+1;
}
}
如果(!空_行(w_tx)){
p[i]=w_tx;
i++;
}
k++;
}
}
返回p;
}
公共静态布尔exi
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);
       }
   }
}