how to print string array onto file?

69 Views Asked by At

I have a string input file and I put the strings into arrays. I only want to print the last element of each string array onto my console and onto a output array. When I run my code, I get the last element of each string array onto my console, but see this on my output file: [Ljava.lang.String;@51d5f7fd

How can I print the actual string array to show up on output file and not its string representation? I'll show you my code so you get a better understanding of what I'm trying to do:

try {
                    br = new BufferedReader(new FileReader("C:\\rd\\bubble.txt"));
                    
                    //first, create new file object
                    File file = new File("C:\\rd\\bubble_out.txt");
                    if(file.exists()) {
                        file.createNewFile();
                    }
                    PrintWriter pw = new PrintWriter(file);
                    
                    
                    
                
                String line = "";
                
                    
                    while((line = br.readLine()) != null) {         //while the line is not equal to null
                    String[] arr = line.split("\\s+");              //split at whitespace
                    System.out.println(arr[arr.length - 1]);
                    pw.println(arr);
                    pw.close();
                    

                        
                    }
         
                }
                
                catch(IOException x) 
             {
                    System.out.println("File not found");
             }
                
                
        }
    }

    }


}

I've tried using Array.toString() method, but I'm not sure how to implement it into my code correctly. I'm currently trying to do that, but if there's an easier way to do this, please let me know.

1

There are 1 best solutions below

3
Unmitigated On
  • Use Arrays.toString to get a readable String representation of the array.
  • Don't close the PrintWriter inside the loop as you have not finished writing all output. You can use try with resources to avoid having to explicitly close it.
try (PrintWriter pw = new PrintWriter(file)) {
    while((line = br.readLine()) != null) {
        String[] arr = line.split("\\s+");
        System.out.println(arr[arr.length - 1]);
        pw.println(Arrays.toString(arr));
    }
}