-2

so I have been trying to convert an object value to string array. basically I'm using stringtokenizer to get the strings from a text file, so I can search for specific values. I am using this library first time. so any help wold be appreciated. here is my main method

 public static void main(String[] args) {
        String[] keys = {"she","sells","sea","shells","by","the","sea","shore"};      
        In in = new In("Protein.txt");
        TST<Integer> st = new TST<Integer>();
        String text1;
        String string = "";
        String [] line1;
        while ((text1 = in.readLine()) != null) {

           String line = text1.trim();
           //System.out.println(line);

           StringTokenizer stt = new StringTokenizer(line);
           while (stt.hasMoreElements()) {
               //System.out.println(stt.nextElement());
               string = String.valueOf(stt.nextElement());
               //line1 = string.split("");
               System.out.println(string);              
           }    
        }
    }
}
Arun Sudhakaran
  • 2,167
  • 4
  • 27
  • 52
Usman Malik
  • 11
  • 2
  • 7

2 Answers2

0

While reading each line as strings put them in an List. We can invoke toArray after reading all the lines.

Other Options is you can use readAllLines from File Object.

balaaagi
  • 502
  • 11
  • 21
0

You can use Apache's FileUtils to work with Files.

String content = FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8);

There are more useful methods like readLines, you can use List<String> instead String[] like below :

List<String> lines = FileUtils.readLines(new File("myfile.txt"), Charsets.UTF_8);
Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85