簡體   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