简体   繁体   English

JAVA:文件I / O

[英]JAVA : file I/O

I have got two text files with data in the following format 我有两个文本文件,数据格式如下

data.txt file as following format data.txt文件,格式如下

A 10
B 20
C 15

data1.txt file is in format (start node,end node, distance): data1.txt文件的格式(开始节点,结束节点,距离):

A B 5 
A C 10
B C 20

I am trying to implement a search strategy, for that I need to load the data from data.txt and ONLY the start node and end node from data1.txt (ie I dont need the distance). 我正在尝试实施一种搜索策略,为此,我需要从data.txt加载数据,并且仅从data1.txt加载开始节点和结束节点(即,我不需要距离)。 I need to store this information in a stack as I think it would be a best data structure for implementing greedy search. 我需要将此信息存储在堆栈中,因为我认为这是实现贪婪搜索的最佳数据结构。

Actually I am not sure how to get started with file I/O to read these files and store them in array to implement greedy search. 实际上,我不确定如何开始使用文件I / O来读取这些文件并将它们存储在数组中以实现贪婪搜索。 So I would highly appreciate any starting idea on how to proceed. 因此,我非常感谢任何有关如何进行的初始想法。

I am new to this, so please bear with me. 我对此并不陌生,所以请多多包涵。 Any help is much appreciated. 任何帮助深表感谢。 Thanks. 谢谢。

EDIT : Here is what I have got till now 编辑 :这是到目前为止我所拥有的

String heuristic_file = "data.txt";
try
    {          

        FileReader inputHeuristic = new FileReader(heuristic_file);
        BufferedReader bufferReader = new BufferedReader(inputHeuristic);
        String line;

        while ((line = bufferReader.readLine()) != null)   
        {
            System.out.println(line);
        }

        bufferReader.close(); 

    } catch(Exception e) {
        System.out.println("Error reading file " + e.getMessage());
    }

My approach, doesn't differ fundamentally from the others. 我的方法与其他方法没有本质上的区别。 Please regard the try/catch/finally blocks. 请注意try / catch / finally块。 Always put the closing statements into the finally block, so the opened file is guaranteed to be closed, even if an exception was thrown while reading the file. 始终将结束语句放入finally块中,因此即使读取文件时引发了异常,也可以确保打开的文件被关闭。

The part between the two //[...] could surely be done more efficient. 肯定可以使/// [...]之间的部分更高效。 Maybe reading the whole file in one take and then parsing the text backwards and searching for a line-break? 也许一次就能读取整个文件,然后向后解析文本并寻找换行符? Maybe a Stream-API supports to set the reading position. 也许Stream-API支持设置阅读位置。 I honestly don't know. 老实说我不知道​​。 I didn't need that, up to now. 到目前为止,我还不需要。

I chose to use the verbose initialization of the BufferedReader, because then you can specify the expected encoding of the file. 我选择使用BufferedReader的详细初始化,因为这样您就可以指定文件的预期编码。 In your case it doesn't matter, since your files do not contain symbols out of the standard ASCII range, but I believe it's a semi-best-practice. 对于您而言,这无关紧要,因为您的文件中不包含超出标准ASCII范围的符号,但是我认为这是最佳做法。

Before you ask: r.close() takes care of closing the underlying InputStreamReader and FileInputStream in the right order, till all readers and streams are closed. 在询问之前: r.close()会按正确的顺序关闭基础InputStreamReaderFileInputStream ,直到关闭所有阅读器和流为止。

public static void readDataFile(String dir, String file1, String file2)
    throws IOException
{
    File datafile1 = new File(dir, file1);
    File datafile2 = new File(dir, file2);

    if (datafile1.exists())
    {
        BufferedReader r = null;

        try
        {
            r = new BufferedReader(
                new InputStreamReader(
                    new FileInputStream(datafile1),
                    "UTF-8"
                )
            );

            String row;

            Stack<Object[]> s = new Stack<Object[]>();
            String[] pair;
            Integer datapoint;

            while((row = r.readLine()) != null)
            {
                if (row != null && row.trim().length() > 0)
                {
                    // You could use " " instead of "\\s"
                    // but the latter regular expression
                    // shorthand-character-class will
                    // split the row on tab-symbols, too
                    pair = row.split("\\s");
                    if (pair != null && pair.length == 2)
                    {
                        datapoint = null;
                        try
                        {
                            datapoint = Integer.parseInt(pair[1], 10);
                        }
                        catch(NumberFormatException f) { }

                        // Later you can validate datapairs
                        // by using
                        // if (s.pop()[1] != null)
                        s.add(new Object[] { pair[0], datapoint});
                    }
                }
            }
       }
       catch (UnsupportedEncodingException e1) { }
       catch (FileNotFoundException e2) { }
       catch (IOException e3) { }
       finally
       {
           if (r != null) r.close();
       }
   }

   // Do something similar with datafile2
   if (datafile2.exists())
   {
       // [...do the same as in the first try/catch block...]

       String firstrow = null, lastrow = null;
       String row = null;
       int i = 0;
       do
       {
          lastrow = row;
          row = r.readLine();
          if (i == 0)
              firstrow = row;
          i++;
       } while(row != null);

       // [...parse firstrow and lastrow into a datastructure...]
   }
}

use split 使用拆分

            while ((line = bufferReader.readLine()) != null)   
            {
                String[] tokens = line.split(" ");
                System.out.println(line + " -> [" + tokens[0] + "]" + "[" + tokens[1] + "][" + tokens[2] + "]");
            }

if you must have this in an array you can use the following: 如果必须将其放在数组中,则可以使用以下命令:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

public class NodeTest {

  public static void main(String[] args) throws ParseException {
    try {          
      File first = new File("data.txt");
      File second = new File("data1.txt");    

      Node[] nodes1 =  getNodes(first);
      Node[] nodes2 =  getNodes(second);

      print(nodes1);
      print(nodes2);
    } 
    catch(Exception e) {
      System.out.println("Error reading file " + e.getMessage());
    }   
  }

  public static final void print(Node[] nodes) {
    System.out.println("======================");
    for(Node node : nodes) {
      System.out.println(node);
    }
    System.out.println("======================");
  }

  public static final Node[] getNodes(File file) throws IOException {
    FileReader inputHeuristic = new FileReader(file);
    BufferedReader bufferReader = new BufferedReader(inputHeuristic);
    String line;
    List<Node> list = new ArrayList<Node>();
    while ((line = bufferReader.readLine()) != null) {
      String[] tokens = line.split(" ");
      list.add(new Node(tokens[0], tokens[1]));               
    }
    bufferReader.close(); 
    return list.toArray(new Node[list.size()]);
  } 
}

class Node {
  String start;
  String end;

  public Node(String start, String end){
    this.start = start;
    this.end = end;
  }

  public String toString() {
    return "[" + start + "][" + end + "]";
  }
}

Something like this? 像这样吗

HashSet<String> nodes = new HashSet<String>();
try(BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
    String line = br.readLine();
    while (line != null) {
        String[] l = line.split(" ");
        nodes.add(l[0]);
        line = br.readLine();
    }
}

try(BufferedReader br = new BufferedReader(new FileReader("data1.txt"))) {
    String line = br.readLine();
    while (line != null) {
        String[] l = line.split(" ");
        if (nodes.contains(l[0]) || nodes.contains(l[1]))
            // Do whatever you want ...
        line = br.readLine();
    }
}       

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM