【问题标题】:Spaces added in while reading from file...?从文件中读取时添加了空格...?
【发布时间】:2012-10-07 03:45:15
【问题描述】:

我正在尝试从一个项目的文件中读取一个单词及其对应的代码。这是我拥有的代码,它读起来很好,只是出于某种原因,在一些但不是全部代码之后添加了空格。我不明白为什么会这样。

代码是:

public void loadDictionary(String file){
    String fileName=file;
    String fileNameTwo=file;
    //Coder c=new Coder();
    String string;
    String code;
    String s=null;
    try{//System.out.println("1");
        FileReader freader=new FileReader(fileName);
        FileReader freaderTwo=new FileReader(fileNameTwo);
        //System.out.println("1");
        BufferedReader inFile=new BufferedReader(freader);
        BufferedReader inFileTwo=new BufferedReader(freaderTwo);
        //System.out.println("2");          
        //System.out.println("3");
        if ((s=inFile.readLine())==null){
            System.out.println("5");
            throw new EmptyFileException("Nothing in file to upload.");
        }
        while ((s=inFileTwo.readLine())!=null){
            //System.out.println("4");
            //System.out.println(s);
            String[] tokens=s.split(" ");
            string=tokens[0];
            //System.out.println(string);
            code=tokens[1];
            //System.out.println(code);
            this.insert(string, code); 
            System.out.println(code+".");               
        }//end while
        //this.printCoder();
    }//end try
    catch(EmptyFileException ex){
    }
    catch(IOException ex){
    System.out.println("Error in uploading dictionary.");
    }   

}//end method

...输出是(代码的):

 5721.
 9963.
 4432   .
 1143   .
 6402   .
 3333   .
 4924       .
 1429       .
 3110   .
 3036   .
 2736   .
 8064.

句点用于显示添加了多少空格。我只是在 system.out.println() 中添加了句点。

编辑:月经不是很正确......但你明白了。有时确实比它显示的更多/更少的空间。

【问题讨论】:

  • 你确定它们是空格吗?由于您要根据空格进行拆分,因此这些更有可能是制表符。重试拆分:String[] tokens=s.split("\\s+"); 并告诉我它是否解决了它或改变了输出中的任何内容。
  • 检查您的数据。 readLine() 不添加空格或其他任何内容。它对数据所做的唯一事情就是删除换行符。

标签: java file spaces


【解决方案1】:

我的猜测是该文件的空格/制表符比您想象的要多 - 您遇到的空格实际上是制表符。

一般情况下,如果要根据空格进行拆分,则应包括所有空格,甚至是制表符。

重试拆分:

String[] tokens=s.split("\\s+");

它将根据正则表达式 "\\s+" 进行拆分 - 这意味着至少(可能更多)某种空间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多