【问题标题】:How to read&Run Multiple variables from bufferedreader in java?如何从 java 中的 bufferedreader 读取和运行多个变量?
【发布时间】:2016-01-28 08:39:00
【问题描述】:

在我将这两个变量 (a),(total) 放在两个不同的类中之前,但我无法获得该类的属性。

所以,

我试图将这两个代码放在一个类中 但两个变量都没有工作 System.out.println("( "+file1.getName() +" )-" +" Total no of words=" + a +"Total repeated words counted:"+total);

都没有工作:

到目前为止我目前的示例输出:

( Blog 39.txt )-总重复词数:4,总词数:0

都没有

( Blog 39.txt )-总重复词计数:0,总词数:82

我需要的输出是:

( Blog 39.txt )-总重复字数:4,总字数:82

当我运行时,“a”或“total”都不起作用。(反之亦然)如果我更改代码(变量)顺序。

任何人都告诉我应该如何获得两个变量输出? :) 我是java初学者

下面是我的代码。

package ramki;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class newrepeatedcount {
    public static void main(String[] args) {
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(".txt");
            }
        };
        File folder = new File("E:\\testfolder\\");
        File[] listOfFiles = folder.listFiles(filter);
        for (int i = 0; i < listOfFiles.length; i++) {
            File file1 = listOfFiles[i];

            BufferedReader ins = null;
            try {
                ins = new BufferedReader(
                        new InputStreamReader(new FileInputStream(file1)));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String line = "", str = "";
            String st = null;
            try {
                st = IOUtils.toString(ins);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // split text to array of words
            String[] words = st.split("\\s");
            // frequency array
            int[] fr = new int[words.length];
            // init frequency array
            for (int i1 = 0; i1 < fr.length; i1++)
                fr[i1] = -1;
            // count words frequency
            for (int i1 = 0; i1 < words.length; i1++) {
                for (int j = 0; j < words.length; j++) {
                    if (words[i1].equals(words[j])) {
                        fr[i1]++;
                    }
                }
            }
            // clean duplicates
            for (int i1 = 0; i1 < words.length; i1++) {
                for (int j = 0; j < words.length; j++) {
                    if (words[i1].equals(words[j])) {
                        if (i1 != j)
                            words[i1] = "";
                    }
                }
            }
            int a = 0;
            try {
                while ((line = ins.readLine()) != null) {
                    str += line + " ";
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            StringTokenizer st1 = new StringTokenizer(str);
            while (st1.hasMoreTokens()) {
                String s = st1.nextToken();
                a++;
            }
            int total = 0;
            for (int i1 = 0; i1 < words.length; i1++) {
                if (words[i1] != "") {
                    // System.out.println(words[i1]+"="+fr[i1]);
                    total += fr[i1];
                }
            }
            System.out.println("( " + file1.getName() + " )-"
                    + "Total repeated words counted:" + total + ","
                    + "total no of words:" + a);
            // System.out.println("total no of words:"+a);
        }
    }
}

【问题讨论】:

  • 我建议你 a) 修复你的格式 b) 当你捕获 IOException 时不要假装它没有发生并继续,你应该只捕获一个可以添加一些值的异常。跨度>
  • 为什么读取文件内容然后丢弃再读取?然后你拆分单词,但稍后在组合的单词上使用 StringTokenizer。我建议您清理此代码并删除无用的内容,以便在调试器中调试代码时轻松查看问题所在。
  • 现在你可以看到我编辑的代码了:
  • 您以两种不同的方式读取文件两次。您应该只读取一次文件,部分原因是这样做效率更高,但主要是因为一旦您读取了所有数据,之后您将无法读取任何内容。这就是为什么您的第二个循环从不读取任何内容的原因。

标签: java arrays string bufferedreader


【解决方案1】:

如果您将流读到底,您将无法继续阅读。 由于您的代码没有在很多方面进行优化,我可以建议一种快速而肮脏的方式来使您的代码工作。在重新计算“a”的值之前,只需初始化分配给变量“ins”的 BufferedReader。

...
try {
    ins = new BufferedReader ( new InputStreamReader(new FileInputStream(file1)));
    while ((line = ins.readLine()) != null) {
        str += line + " ";
    }
} catch (IOException e) {
    e.printStackTrace();
}
...

【讨论】:

  • 我以前做过,但现在它没有计算“总”值。
  • 作为免责声明:有很多东西可以而且应该改变你的代码。我提供的更改不是我最终会推荐的,但它会让你的代码工作。
  • “在我的机器上工作”。不,老实说:我看不出有什么理由,为什么它不能根据我的建议计算“总数”,事实上,它会在我的机器上打印出来。
  • 在你的建议之前我有(博客 39.txt)-总重复单词计数:4,总单词数:0。根据你的建议,我得到了这个(博客 39.txt)-重复单词总数计数:0,总字数:82。它显示 0。:/
  • 请创建一个包含“a b c a b”的文本文件。我得到( test.txt ) - 重复单词总数:2,单词总数:5
【解决方案2】:

我不确定这是否是最好的解决方案,但这会给你一个集合或地图(在内部你可以转换它在你的文本中出现的次数。然后你可以根据你的要求使用它。

 import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

 public class NewRepeatedCount  {

    public static void main(String... arg0)
    {
     BufferedReader br = null;
     Map<String, Integer> counterMap = new HashMap<String, Integer>();

        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader("C:\\testing.txt"));

            while ((sCurrentLine = br.readLine()) != null) {
                String[] words = sCurrentLine.split("\\s");
                for(String word : words)
                {
                    int count = 1;
                    if(counterMap.get(word) != null)
                    {
                        count = counterMap.get(word);
                        count++;
                        counterMap.put(word, count);
                    }else{
                        counterMap.put(word, count);
                    }

                }
            }
            System.out.println(counterMap.entrySet());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
 }

【讨论】:

    【解决方案3】:

    每当您进行这样的数据处理时,Java 8 的 Stream API 都可能是最佳选择。

    // get all the files under this folder
    Files.walk(Paths.get("E:\\testfolder\\"))
            // keep all the files ending in .txt
            .filter(p -> p.toString().toLowerCase().endsWith(".txt"))
            .forEach(p -> {
                try {
                    // process all the lines of the file.
                    Map<String, Long> wordCount = Files.lines(p)
                            // break the lines into words
                            .flatMap(l -> Stream.of(l.split("\\s")))
                            // collect the words and count them
                            .collect(Collectors.groupingBy(w -> w, Collectors.counting()));
                    // find how many values are more than 1
                    long wordDuplicates = wordCount.values().stream().filter(l -> l > 1).count();
                    // get the sum of all the values.
                    long totalWords = wordCount.values().stream().mapToLong(l -> l).sum();
                    System.out.println(p + " has " + wordDuplicates + " duplicates and " + totalWords + " words");
                // catch the IOException at the end because you can't do anything more with the file if this happens.
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
    

    【讨论】:

      猜你喜欢
      • 2014-02-09
      • 1970-01-01
      • 2019-03-31
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      相关资源
      最近更新 更多