-1

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
MajorMike
  • 11
  • 3

1 Answers1

0
  • 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));
    }
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • this worked(thank you so much), but i have the enitre string array on the output file instead of the last element of the string array. how would i be able to do that? – MajorMike Jan 18 '23 at 23:26
  • @subpolly So you want `pw.println(arr[arr.length-1]);` just like you did with `System.out`. – Unmitigated Jan 18 '23 at 23:27
  • yeah pw.println(arr[arr.length-1]) worked. Thanks, i really appreciate your help. – MajorMike Jan 18 '23 at 23:31