-2

Im working on a project for school, and im stuck at reading a txt file, i tried using this code

public static String txt (String a) 
   {
      String[] Text= new String[Readfile.counter(a)]; // Creates a string array for every word
      String s="";  
      int i=0;
      try{
         Scanner scan =new Scanner(new File(a));

         while(scan.hasNext()){

            s =scan.next(); // läser en rad från fil till s
            Text[i]=s;
            i++;
           // System.out.print(s + " "); // skriver ut den 

         }

      }
      catch( Exception exp) {}
      String txt= Arrays.toString(Text);
      return txt;
      }

wanted to save the strings in an array as it loops then turn it into a string, but the problem here is that the results will have brackets"[]" and commas "," in it. Is there any way to read the entire txt file and save it in a single variable?

1 Answers1

0

Don't save the text of string in a array.Use this code.

public static String txt (String a) 
   {

      String s="";  
String text="";     
 int i=0;
      try{
         Scanner scan =new Scanner(new File(a));

         while(scan.hasNext()){

            s =scan.next(); // läser en rad från fil till s
          text=text+s;
            i++;
           // System.out.print(s + " "); // skriver ut den 

         }

      }
      catch( Exception exp) {}

      return text;
      }
bit-shashank
  • 887
  • 11
  • 27