将文件的内容分配给变量

时间:2017-03-03 19:40:55

标签: java file

我目前正在处理我的介绍编程类的作业,我需要能够将文件的内容分配给变量。该文件包含文本段落。我需要能够最终计算文本文件中的所有字符和单词。

到目前为止我所拥有的:

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

public class CountWords {
  public static void main(String[] args) throws IOException {

    File inFile = new File("CountWordsTestFile.txt");
    Scanner input = new Scanner(inFile);

    String text = input.nextLine();

    int words = 0, cha = text.length(), character = 0;


        System.out.println(text);

    System.out.println("The file contains");
    System.out.println(words + " words");
    System.out.println((cha + 1) + " characters");
        input.close();
  }
}

2 个答案:

答案 0 :(得分:0)

package test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


public class ReadFile {

    public static void readWords(String filePath) {
        int words = 0;
        int characters = 0;

        BufferedReader br = null;
        FileReader fr = null;
        try {
            fr = new FileReader(filePath);
            br = new BufferedReader(fr);
            String line;
            while ((line = br.readLine()) != null) {
                if (line.trim().replaceAll(" +", " ").length() == 0) continue;
                characters += line.length();

                line = replaceAllSpecialCharacters(line);
                words += line.split("\\s").length;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)
                    br.close();

                if (fr != null)
                    fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Words : " + words);
        System.out.println("Characters : " + characters);


    }

    public static String replaceAllSpecialCharacters(String line) {

        return line.replaceAll(" +", " ").replaceAll("[^\\p{L}\\p{Z}]", " ").trim();

    }

    public static void main(String[] a) {
        readWords("CountWordsTestFile.txt");
    }

}

编辑: 简单代码作为您的要求

package test;

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


public class ReadFile {

    public static void readWords(String filePath) {
      int words=0,characters=0;

        Scanner in= null;
        try {
            in = new Scanner(new File(filePath));


        while (in.hasNextLine()){
            //Here you have the value line by line

            String line =in.nextLine();
            //if line is empty or has only spaces continue to the another line
            if(line==null||line.trim().length()==0)continue;

            //add the length for each line to compute characters

            characters+=line.length();



            //replace multiple spaces with one space
           line=line.replaceAll(" +"," ");

            //trim the line to remove spaces 

            line=line.trim();

            //split the line with space to get array of words

            String []wordsArray=line.split("\\s");




            //the length of this array is the # of words in this line

            words+=wordsArray.length;

        }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println("Words : " + words);
        System.out.println("Characters : " + characters);
    }

    public static void main(String[] a) {
        readWords("CountWordsTestFile.txt");
    }



}

答案 1 :(得分:0)

以下是Java程序的简化版本,用于计算文件中的字符和单词。我假设文件是​​一个文本文件,文件中的单词只用一个或多个空格分隔,而不是用任何分隔符。

public class CountWords {
    public static void main(String[] args) {
        //Initializing counter for words and characters in the file
        int words = 0, chars = 0;
        File inFile = new File("CountWordsTestFile.txt");
        try {
            Scanner scanner = new Scanner(inFile);
            while(scanner.hasNextLine()){
                //Read the line and assign it to a string
                String str = scanner.nextLine();
                //Increase the counter for no of characters
                chars = chars + str.length();
                //Split the line by spaces and store in an array
                String[] strArr = str.split("[ ]+");
                //Increase the counter for no of words 
                words = words + strArr.length;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } 
        System.out.println("The file contains");
        System.out.println(words + " words");
        System.out.println(chars + " characters");
    }
}

希望它符合您的要求。