Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何为用户输入搜索的文本文件创建数组?_Java - Fatal编程技术网

Java 如何为用户输入搜索的文本文件创建数组?

Java 如何为用户输入搜索的文本文件创建数组?,java,Java,我正在做一项作业,其中程序需要读取由用户输入定位的文件。 扫描文件并创建阵列。 数组以字符串形式存储在单词中,并输出一个单词的使用次数。 然后,输出被打印到一个新文件中 package TestFileReader; import java.io.*; import java.util.*; public class ReadFile { public static void main(String[] args) { //Prompts user for file by aski

我正在做一项作业,其中程序需要读取由用户输入定位的文件。 扫描文件并创建阵列。 数组以字符串形式存储在单词中,并输出一个单词的使用次数。 然后,输出被打印到一个新文件中

package TestFileReader;

import java.io.*;
import java.util.*;

public class ReadFile
{

public static void main(String[] args)
{
    //Prompts user for file by asking for its location
    Scanner keys = new Scanner(System.in);
    String fileName;

    System.out.print("Enter file location, or 'Quit' to quit: ");
    fileName = keys.nextLine();

    Scanner textFile = null;

    //try catch block for exception
    try
    {
        textFile = new Scanner(new File(fileName));
    }
    catch(FileNotFoundException s)
    {
        System.out.println("File not found, confirm location: ");
    }

    //File will be read continuously until there is no next line
    while(textFile.hasNextLine())
    {
        String contents = textFile.nextLine();
        System.out.println(contents);
    }

    textFile.close();



    //New Class for saving read into array
}
}

在我准备以下示例的同时,Jan也正确地回答说可以使用
HashMap

        HashMap<String,Integer> map=new HashMap<String,Integer>();

        //File will be read continuously until there is no next line
        while(textFile.hasNextLine())
        {
            String line = textFile.nextLine();

            // Split line into words
            String words[]=line.split("\\s+");
            for (String word : words)
            {
                // Get current word count
                Integer count=map.get(word);
                if (count==null)
                {
                    // Create a new counter for a new word
                    map.put(word,1);
                }
                else
                {
                    // Increase existing word counter
                    map.put(word,count+1);
                }
            }
        }

        // Output result
        for (Map.Entry<String,Integer> entry : map.entrySet())
        {
            System.out.println(entry.getKey()+": "+entry.getValue());
        }

        textFile.close();
示例输出:

a: 1
Wuff!: 1
test: 2
another: 1
This: 2
is: 2

由于Java8,您还可以使用Streams API来完成此任务

import java.io.IOException;
导入java.nio.file.Files;
导入java.nio.file.path;
导入java.util.Scanner;
导入java.util.stream.collector;
导入java.util.stream.stream;
公共类读取文件{
公共静态void main(字符串[]args){
//通过询问文件位置提示用户输入文件
扫描仪键=新扫描仪(System.in);
字符串文件名;
System.out.print(“输入文件位置,或“退出”退出:”);
fileName=keys.nextLine();
try(Stream=Files.line(path.get(fileName))){
stream.flatMap(s->stream.of(s.split(\\W)))
.filter(s->s!=null&!s.isEmpty())
.collect(Collectors.toMap(s->s,s->1,Integer::sum))
.forEach((k,v)->System.out.println(k+“:”+v));
}捕获(IOE异常){
System.out.println(“无法读取文件:+文件名”);
}
}
}

您的任务有任何限制吗?我的意思是你能使用JDK中的所有类吗?例如,您是否可以使用class
java.nio.file.Files
?读取一行后,您可以按定义的字符分割该行,例如空字符串或逗号或其他字符。然后,每个单词和相应的计数可以存储在
映射中。读完后,你把这张地图的每一条记录都写进一个文件。非常感谢。在过去的一周里,我一直在努力做这个作业。谢谢:")。如何学习Java?我的教授不教书,在实践中学习。当然,还可以与其他开发人员交谈。在公司里,我们讨论我们的问题和解决方案,互相指导。很好的例子,@Stefan。您可能希望养成的一个习惯是:永远不要声明集合比它们需要的更具体。因此,map的声明应该是map map=newhashmap();您现在使用HashMap实现它的事实是一个细节,它应该只作为对象创建的一部分存在。明天您可能会将其更改为树映射,这样您就不需要依赖于哈希映射的任何下游代码。这是一个品味问题。如果我不使用比需要更多不同的类类型,那么这样的示例更容易阅读。
a: 1
Wuff!: 1
test: 2
another: 1
This: 2
is: 2