首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

大神:怎么将文件中词语存入String[]中

2013-07-09 
请教各位大神:如何将文件中词语存入String[]中如题,请教各位大神。我有一个保存有若干词语的txt文件,词与词

请教各位大神:如何将文件中词语存入String[]中
如题,请教各位大神。我有一个保存有若干词语的txt文件,词与词之间用空格隔开。如何将这些词语保存在String[]中,每个词语都是数组中的一项。最好能贴出代码。谢谢 String 自然语言处理 java
[解决办法]
        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(); 
        } 

------解决方案--------------------



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

[解决办法]
引用:

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

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

热点排行
Bad Request.