开发者

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

开发者 https://www.devze.com 2023-03-30 01:14 出处:网络
I am using this code to read a txt file, line by line. // Ope开发者_如何转开发n the file that is the first command line parameter

I am using this code to read a txt file, line by line.

// Ope开发者_如何转开发n 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. 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.


Have a look at the replace method in String and call it on strLine before putting it in the array.


You can use a Scanner which by default uses white space to separate tokens. Have a look at this tutorial.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号