【问题标题】:Read the each string text from file in java从java中的文件中读取每个字符串文本
【发布时间】:2016-02-23 06:37:20
【问题描述】:

我是java新手。我只想读取java中的每个字符串并在控制台上打印它。

代码:

public static void main(String[] args) throws Exception {

    File file = new File("/Users/OntologyFile.txt");
    try {
        FileInputStream fstream = new FileInputStream(file);
        BufferedReader infile = new BufferedReader(new InputStreamReader(
                fstream));
        String data = new String();
        while ((data = infile.readLine()) != null) { // use if for reading just 1 line
            System.out.println(""+data);
        }
    } catch (IOException e) {
        // Error
    }
}

如果文件包含:

Add label abc to xyz
Add instance cdd to pqr

我想从文件中读取每个单词并将其打印到新行,例如

Add
label
abc
...

然后,我想提取特定字符串的索引,例如获取abc的索引。

谁能帮帮我?

【问题讨论】:

标签: java string file io


【解决方案1】:

听起来您希望能够做两件事:

  1. 打印文件中的所有单词
  2. 搜索特定单词的索引

在这种情况下,我建议扫描所有行,用任何空白字符(空格、制表符等)分割并存储在一个集合中,以便您以后可以搜索它。不是问题 - 你可以有重复,在这种情况下你想打印哪个索引?首先?最后?全部?

假设单词是唯一的,您可以这样做:

public static void main(String[] args) throws Exception {

    File file = new File("/Users/OntologyFile.txt");
    ArrayList<String> words = new ArrayList<String>();
    try {
        FileInputStream fstream = new FileInputStream(file);
        BufferedReader infile = new BufferedReader(new InputStreamReader(
                fstream));
        String data = null;
        while ((data = infile.readLine()) != null) {
            for (String word : data.split("\\s+") {
                words.add(word);
                System.out.println(word);
            }
        }
    } catch (IOException e) {
        // Error
    }

    // search for the index of abc:
    for (int i = 0; i < words.size(); i++) {
        if (words.get(i).equals("abc")) {
             System.out.println("abc index is " + i);
             break;
        }
    }
}

如果您不中断,它将打印abc 的每个索引(如果单词不是唯一的)。如果单词集非常大,当然可以进行更多优化,但是对于少量数据,这应该就足够了。

当然,如果您事先知道要打印哪些单词的索引,您可以放弃额外的数据结构(ArrayList)并在扫描文件时简单地打印它,除非您想要打印(单词和特定索引)在输出中分开。

【讨论】:

    【解决方案2】:

    使用正则表达式 \\s+ 将收到的 String 拆分为任何空格,并使用 for 循环打印出结果数据。

    public static void main(String[] args) {    // Don't make main throw an exception
    
        File file = new File("/Users/OntologyFile.txt");
    
        try {
            FileInputStream fstream = new FileInputStream(file);
            BufferedReader infile = new BufferedReader(new InputStreamReader(fstream));
    
            String data;
            while ((data = infile.readLine()) != null) {
                String[] words = data.split("\\s+");    // Split on whitespace
                for (String word : words) {             // Iterate through info
                    System.out.println(word);           // Print it
                }
            }
    
        } catch (IOException e) {
            // Probably best to actually have this on there
            System.err.println("Error found.");
            e.printStackTrace();
        }
    }
    

    【讨论】:

      【解决方案3】:

      在打印输出之前添加一个 for-each 循环:-

      while ((data = infile.readLine()) != null) { // use if for reading just 1 line
        for(String temp : data.split(" "))
        System.out.println(temp); // no need to concatenate the empty string.
      }
      

      这将自动打印从文件中读取的每个字符串行中获得的单个字符串,并将其打印到新行中。

      然后,我想提取特定字符串的索引,对于 实例获取abc的索引。

      我不知道您实际上在说什么索引。但是,如果您想从正在读取的各个行中获取索引,请添加一个临时变量,并将 count 初始化为 0。

      在此处将其递增直到 d 等于 abc。喜欢,

      int count = 0;
      for(String temp : data.split(" ")){
       count++;
       if("abc".equals(temp))
        System.out.println("Index of abc is : "+count);
       System.out.println(temp);
      }
      

      【讨论】:

        【解决方案4】:

        使用Split()Class String中提供的函数。您可以根据需要进行操作。

        使用length 关键字遍历整个 如果任何非字母字符获取substring()并将其写入新行。

        【讨论】:

          【解决方案5】:
                List<String> words = new ArrayList<String>();
                 while ((data = infile.readLine()) != null) { 
                     for(String d : data.split(" ")) {
                       System.out.println(""+d);
                     }
                     words.addAll(Arrays.asList(data));   
                   }
              //words List will hold all the words. Do words.indexOf("abc") to get index
          
          
               if(words.indexOf("abc") < 0) {
                  System.out.println("word not present");     
                } else {
                 System.out.println("word present at index " + words.indexOf("abc"))
                }
          

          【讨论】:

          • 如果在列表中找不到 abc,它将打印 -1。如果找不到单词,你想要什么行为?
          • 从逻辑上讲,不应该打印。它不是一个有效的索引。但是,是否要保持原样取决于您(以这种方式可读性不强)。
          猜你喜欢
          • 2015-05-09
          • 2016-02-12
          • 1970-01-01
          • 2013-05-17
          • 2012-11-12
          • 1970-01-01
          • 2016-07-14
          • 2016-01-15
          • 2016-07-01
          相关资源
          最近更新 更多