gpt4 book ai didi

java - 从文件读取时添加了空格...?

转载 作者:行者123 更新时间:2023-12-02 00:10:25 26 4
gpt4 key购买 nike

我正在尝试从项目文件中读取单词及其相应的代码。这是我的代码,读起来很好,只是出于某种原因在一些(但不是全部)代码后面添加了空格。我不明白为什么会发生这种情况。

代码是:

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+");

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

关于java - 从文件读取时添加了空格...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12924923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com