韩唐伯石 2020-11-19 19:59 采纳率: 55%
浏览 25
已结题

关于IOsystem reader里用split方法读取的问题?

老师留作业,要扫描一个文件并且将文件中的单词逐个添加进一个List<String>里去。那个文件每个单词占一行,我想用 .add(split("\n")[i])这个方法在一个循环里实现,但是我发现在\n处分割只能把第一个元素添加进List里,之后的全部没有。我用打印了一下split("\n").length,发现长度只有一。是因为read的扫描器只能扫描一行吗?

后面是代码,求教,谢谢!

public class WordFisher 
{
	public HashMap<String, Integer> vocabulary; 
	private List<String> stopwords;// (to be instantiated as an ArrayList)
	private String inputTextFile; 
	private String stopwordsFile; 
	
	public WordFisher(String inputTextFile, String stopwordsFile) throws IOException
	{
		this.inputTextFile = inputTextFile;
		this.stopwordsFile = stopwordsFile;
		stopwords = new LinkedList<String>();
		getStopwords();
	}
	
	private void getStopwords() throws IOException
	{
		try 
		{
			BufferedReader input = new BufferedReader(new FileReader(stopwordsFile));
			String read = input.readLine();
			int i = 0;
			String[] string = read.split("n");
			while(i < string.length)
			{
				stopwords.add(string[i]);
				i++;	
			}
			input.close();
			
			for(int k = 0; k < stopwords.size(); k++)
			{
				System.out.println(stopwords.get(k));
			}
		} 
		catch (FileNotFoundException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
}
  • 写回答

1条回答 默认 最新

  • 西安站 2020-11-19 22:36
    关注

    `input.readLine()` 这个方法就是读取一行的数据,

    而你文件每个单词一行, 应该按下面的来

    String line;
    while((line = input.readLine()) != null) {
        // do something with line
    }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 8月7日
  • 已采纳回答 7月30日

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号