1

How do I get data from a text file and save it into a string?

For example, my text file has the numbers 1, 4, 5, 6, 8, and 10.4. These numbers can be on the same line or on separate lines. I want to concatenate them into a string, like so: 1 4 5 6 8 10.4

import java.io.File;

import java.io.FileNotFoundException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;

public class f {
    public static void main(String args[]) {
        int count = 0;
        double totalcount = 0;
        double average = 0;
        Scanner read = new Scanner(System.in);
        Scanner file;
        String input = "";
        String test = "";

        double[] array1 = new double[100];

        while (true) {
            System.out.println("Enter name of file or enter quit to exit");
            input = read.next();
            if (input.equalsIgnoreCase("quit")) {
                break;
            }

            try {
                file = new Scanner(new File(input));
                if (!file.hasNextLine()) {
                    System.out.println(input + " file is empty");
                }

                while (file.hasNext()) {
                    totalcount = totalcount + file.nextDouble();
                    count++;
                }
                while (file.hasNext()) {
                    test = test + (" ") + file.next();
                }

                System.out.println("bla" + test);

                average = totalcount / count;

                DecimalFormat df = new DecimalFormat("#.###");
                df.setRoundingMode(RoundingMode.CEILING);

                System.out.println("\nCount: " + count);
                System.out.println("Total: " + df.format(totalcount));
                System.out.println("Average: " + df.format(average));
                System.out.println();

            } catch (FileNotFoundException e) {
                System.out.println(input + " doesn't exist");
            }
        }
    }
}

My code does not work correctly.

MultiplyByZer0
  • 4,341
  • 3
  • 27
  • 46
  • 1
    Sounds great. Any errors so far with this request? – OneCricketeer Jun 10 '17 at 06:28
  • Well this is all I have so far but it doesnt work. while (file.hasNext()) { test = test + (" ") + file.next(); } – EmmanoelD97 Jun 10 '17 at 06:30
  • Can you please show a [mcve] in the question itself? Please **[edit]** – OneCricketeer Jun 10 '17 at 06:31
  • I just posted what I have so far, it is kind of a mess, my objective is to get a file name from a user then save the contents of a file to a string to then process. – EmmanoelD97 Jun 10 '17 at 06:34
  • You exhausted the whole scanner after the first `while (file.hasNext()) {` – OneCricketeer Jun 10 '17 at 06:35
  • Is your goal to read an entire file into a string, or read it word by word / number by number? – OneCricketeer Jun 10 '17 at 06:36
  • If all you want is the string. https://stackoverflow.com/questions/326390/how-do-i-create-a-java-string-from-the-contents-of-a-file but I think you actually want a list of integers, it seems – OneCricketeer Jun 10 '17 at 06:38
  • youre right haha, I just combined the two but the problem now is that the while loop just reads one line and skips one so instead of 1 2 3 4 5 6 it prints 1 3 5 – EmmanoelD97 Jun 10 '17 at 06:38
  • Also, there's this. https://stackoverflow.com/questions/22213916/reading-integers-from-file-into-an-arraylist – OneCricketeer Jun 10 '17 at 06:39
  • I think your skipping problem is mentioned here https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo – OneCricketeer Jun 10 '17 at 06:40
  • @EmmanoelD97 I understand this: Numbers in text file can be separated by one white space or by one line break. Numbers can be integer or decimal. Numbers in string variable are separed by one white space. Is this correct? – Dani Jun 10 '17 at 07:27

2 Answers2

1

Your code is working fine, the problem is, you trying to access content of your file two times.after first while loop , the hasnext() method will return false.because you already accessed all the element in first while loop. so it will not execute -

                while (file.hasNext()) {
                test = test + (" ") + file.next();
                }

Other than that your code is fine. if you want store it in string also then do small modification in your first while loop as below-

while (file.hasNext()) {
      Double d=file.nextDouble();
      test = test + (" ")+d;
      totalcount = totalcount + d;
      count++;
 }

I think this will give you what you want.

gajju_15
  • 473
  • 4
  • 15
-1

Hello i think below code will be useful for you ,as per your question i have txt file with data , first i am getting the location of file & then i am trying to get the content , at last i am printing it to the console

File f = new File("D:\\temp.txt");

    String content11 = FileUtils.readFileToString(f);

      System.out.println(content11);