将对象值转换为字符串数组

时间:2017-11-22 05:42:22

标签: java stringtokenizer

所以我一直在尝试将对象值转换为字符串数组。基本上我正在使用stringtokenizer从文本文件中获取字符串,因此我可以搜索特定的值。我是第一次使用这个库。所以任何帮助都值得赞赏。这是我的主要方法

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

2 个答案:

答案 0 :(得分:0)

将每行读取为字符串时将它们放入List中。我们可以在读完所有行后调用toArray。

其他选项是您可以使用文件对象中的readAllLines

答案 1 :(得分:0)

您可以使用Apache's FileUtils来处理File s。

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

有更多有用的方法,例如readLines,您可以使用List<String>代替String[],如下所示:

List<String> lines = FileUtils.readLines(new File("myfile.txt"), Charsets.UTF_8);
相关问题