简体   繁体   English

Java:读取txt文件并将其保存在字符串数组中但没有反斜杠(空格)吗?

[英]Java: Read a txt file and save it in an array of strings but without backslashes (spaces)?

I am using this code to read a txt file, line by line. 我正在使用此代码逐行读取txt文件。

// Open the file that is the first command line parameter 
FileInputStream fstream = new FileInputStream("/Users/dimitramicha/Desktop/SweetHome3D1.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
int i = 0;
while ((strLine = br.readLine()) != null) {
    str[i] = strLine;
    i++;
}
// Close the input stream
in.close();

and I save it in an array. 然后将其保存在数组中

Afterwards, I would like to make an if statement about the Strings that I saved in the array. 之后,我想对保存在数组中的字符串进行if声明。 But when I do that it doesn't work, because (as I've thought) it saves also the spaces (backslashes). 但是,当我这样做时,它是行不通的,因为(正如我认为的那样)它还节省了空间(反斜杠)。 Do you have any idea how I can save the data in the array but without spaces? 您是否知道如何将数据保存在数组中但没有空格?

I would do: 我会做:

strLineWithoutSpaces = strLine.replace(' ', '');
str[i] = strLineWithoutSpaces;

You can also do more replaces if you find other characters that you don't want. 如果您发现其他不需要的字符,也可以进行更多替换。

看一下String中的replace方法,并在将其放入数组之前在strLine上调用它。

You can use a Scanner which by default uses white space to separate tokens. 您可以使用默认情况下使用空格分隔令牌的扫描仪 Have a look at this tutorial. 看一下教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM