Search code examples
javafilecharreturn

Function to read file passing it by parameter


Hi guys I'm having difficulty with a method to read file.I have not found anything in the documentation.

I'm trying to return an array of char.

public class ReadFile {

    public static void main(String[] args) throws IOException {
        
        File  f = new File("word.txt");
     
        char [] word=ReadWordFile(f);
        
        System.out.println(word);

    }
    
    
    //1.Read words  from File and return as arr of char
    public static  char [] ReadWordFile(File f) throws IOException {
         BufferedReader br
         = new BufferedReader(new FileReader(f));
         
         char [] aux = null;

     // Declaring a string variable
     String st;
     // Condition holds true till
     // there is character in a string
     while ((st = br.readLine()) != null)

        st+=aux;

     return aux;    
    }

Solution

  • Nothing changes aux in your code:

    char [] aux = null;
    // Declaring a string variable
    String st;
    // Condition holds true till
    // there is character in a string
    while ((st = br.readLine()) != null)
      st+=aux;
    return aux;
    

    Concatenate all read strings and then get the char array from:

    String st = "", read = null;
    // Condition holds true till
    // there is character in a string
    while ((read = br.readLine()) != null)
      st += read;
    return st.toCharArray();