如题,请教各位大神。我有一个保存有若干词语的txt文件,词与词之间用空格隔开。如何将这些词语保存在String[]中,每个词语都是数组中的一项。最好能贴出代码。谢谢String自然语言处理java

解决方案 »

  1.   

            try { 
                    String encoding="GBK"; 
                    File file=new File(filePath); 
                    if(file.isFile() && file.exists()){ //判断文件是否存在 
                        InputStreamReader read = new InputStreamReader( 
                        new FileInputStream(file),encoding);//考虑到编码格式 
                        BufferedReader bufferedReader = new BufferedReader(read); 
                        String lineTxt = null; 
                        String str2 = "";
                        while((lineTxt = bufferedReader.readLine()) != null){ 
                             str2+=lineTxt;                        
                        } 
                        read.close(); 
                        String[] arr = str2.split(" ");
                        for...
            }else{ 
                System.out.println("找不到指定的文件"); 
            } 
            } catch (Exception e) { 
                System.out.println("读取文件内容出错"); 
                e.printStackTrace(); 
            } 
      

  2.   


        public static void main(String... args) throws FileNotFoundException{
            List<String> l = new ArrayList<>();
            Scanner reader = new Scanner(new File("your_file_path"))
                    .useDelimiter(" ");
            while (reader.hasNext()){
                l.add(reader.next());
            }
            String[] array = l.toArray(new String[1]);
            System.out.print(Arrays.toString(array));
        }
      

  3.   

    +1
    稍微优化下:
    Scanner reader = new Scanner(new File("your_file_path"))
                    .useDelimiter("\\s+");