-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);              
           }    
        }
    }
}
9
  • What error are you facing? Commented Nov 22, 2017 at 5:47
  • No error. I am able to convert object value to string as 'string = String.valueOf(stt.nextElement());'. what I need to do is to convert object value to string array. but i don't know how to do it. I searched it but couldn't find any help Commented Nov 22, 2017 at 5:52
  • Ok. Are you looking for other options? Can you please elaborate more on the question? Commented Nov 22, 2017 at 5:54
  • Yes. i can use jsoup but I don't know its working. how it converts text file into string array. Commented Nov 22, 2017 at 5:56
  • right now I just want to convert text file into string array. It would be very helpful if u could guide me to the right path Commented Nov 22, 2017 at 5:57

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.