繁体   English   中英

JAVA:文件I / O

[英]JAVA : file I/O

我有两个文本文件,数据格式如下

data.txt文件,格式如下

A 10
B 20
C 15

data1.txt文件的格式(开始节点,结束节点,距离):

A B 5 
A C 10
B C 20

我正在尝试实施一种搜索策略,为此,我需要从data.txt加载数据,并且仅从data1.txt加载开始节点和结束节点(即,我不需要距离)。 我需要将此信息存储在堆栈中,因为我认为这是实现贪婪搜索的最佳数据结构。

实际上,我不确定如何开始使用文件I / O来读取这些文件并将它们存储在数组中以实现贪婪搜索。 因此,我非常感谢任何有关如何进行的初始想法。

我对此并不陌生,所以请多多包涵。 任何帮助深表感谢。 谢谢。

编辑 :这是到目前为止我所拥有的

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

我的方法与其他方法没有本质上的区别。 请注意try / catch / finally块。 始终将结束语句放入finally块中,因此即使读取文件时引发了异常,也可以确保打开的文件被关闭。

肯定可以使/// [...]之间的部分更高效。 也许一次就能读取整个文件,然后向后解析文本并寻找换行符? 也许Stream-API支持设置阅读位置。 老实说我不知道​​。 到目前为止,我还不需要。

我选择使用BufferedReader的详细初始化,因为这样您就可以指定文件的预期编码。 对于您而言,这无关紧要,因为您的文件中不包含超出标准ASCII范围的符号,但是我认为这是最佳做法。

在询问之前: 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...]
   }
}

使用拆分

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

如果必须将其放在数组中,则可以使用以下命令:

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 + "]";
  }
}

像这样吗

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