需要帮助阅读文件内的数字

时间:2017-04-30 02:15:09

标签: java

  • 首先我创建一个txt文件(a.txt) - DONE
  • 从 - 到(如5-10)--DONE
  • 创建10个随机数
  • 我在txt文件中写了这个号码--DONE
  • 我想检查一下是否写完 - DONE
  • 现在我需要找到:数字,最大,最小,数字的总和 但我无法调用该文件并在文件中搜索(a.txt)。我只是发送最后一部分。其他部分工作。我需要一些帮助来理解。它也在另一种方法中。不是主要的

    Scanner keyboard = new Scanner(System.in);
    boolean again = true;
    int max = Integer.MIN_VALUE;
    int min = Integer.MAX_VALUE;
    int a = 0;
    int count = 0;
    
    System.out.println("Enter the filename to write into all analysis: ");
    outputFileName = keyboard.nextLine();
    
    File file2 = new File(outputFileName);
    if (file2.exists()) {
        System.out.println("The file " + outputFileName +
            " already exists. Will re-write its content");
    }
    
    
    try {
        PrintWriter yaz = new PrintWriter(file2);
    
        // formulas here. created file a.txt  need to search into that file biggest smallest and sum of numbers
    
        yaz.println("Numeric data file name: " + inputFileName);
        yaz.println("Number of integer: " + numLines);
        yaz.println("The total of all integers in file: " + numLines); //fornow
        yaz.println("The largest integer in the set: " + max);
        yaz.println("The smallest integer in the set " + min);
    
        yaz.close();
        System.out.println("Data written to the file.");
    } catch (Exception e) {
        System.out.printf("ERROR reading from file %s!\n", inputFileName);
        System.out.printf("ERROR Message: %s!\n", e.getMessage());
    
    }
    

2 个答案:

答案 0 :(得分:0)

您需要将文件读入内存。一种方法是将文件的文本移动到String中。

这篇文章将对您有所帮助:Reading a plain text file in Java

以下是相关代码:

try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    } 
    String everything = sb.toString();
} 

答案 1 :(得分:0)

所以你想要一个代码来读取文本文件并给你最大,最小和平均。 您可以使用扫描程序类,并使用 hasNextInt()查找整数

        File f = new File("F:/some_text_file.txt"); // input your text file here
    if(f.exists()){
        try{    
            Scanner sc = new Scanner(f);
            int max = Integer.MIN_VALUE;
             int min = Integer.MAX_VALUE;
             int temp=0, i=0;
             double sum=0;
            while(sc.hasNextInt()){
                temp = sc.nextInt();
                if(temp>max) max = temp;
                if(temp<min) min =temp;
                sum+=(double) temp;
                i++;

            }
            System.out.println("average : " +sum/i);    
            System.out.println("large : "+max);
            System.out.println("small :"+min);
            sc.close();
        }catch(Exception e){
            e.printStackTrace();
        }       
    }

看看是否有效