这个问题在这里已有答案:
读取并拆分文本文件(java) 2个答案我有这个分配,我必须做一个简单的购物界面,用户可以在其中注册,登录和购买。 因为它是一个简单的,我甚至不想到安全问题或任何事情,所以当一个新用户注册我只是拿每个文本框的数据(名称,电子邮件,国家等)添加到arraylist,然后将其存储到txt文件中,每行一个用户。 当你打开txt文件时,每一行看起来像这样:
[姓名,电子邮件,密码,国家,州,ADRESS,生日]
现在我正在尝试登录方法,我只需要将文本框上的输入与每个用户的每个arraylist上的已定义索引进行比较(用户[1]用于电子邮件,用户[2]用于密码),但是当我从行读取文件行时,它只是将整个arraylist变成一个大字符串,如下所示:
"[Name,email,password,Country,State,adress,birthdate]"有没有办法把每一行都读成一个arraylist?
顺便说一下,我正在使用BufferReader和FileReader库
(英语不是我的母语所以,如果有什么不清楚的话,请问我可以试着澄清一下)
This question already has an answer here:
Read and split a text file (java) 2 answersI have this assigment where I have to make a simple shopping interface, in which the users can register, log in and buy. As it's a simple one I'm not bothering to even think of security issues or anything, so when a new user registers I just take the data of each textbox(name,email,country, etc)add it to an arraylist, and then store that into a txt file, with one user per line. When you open up the txt file each line looks like this:
[Name,email,password,Country,State,adress,birthdate]
now I'm trying to do the log in method, in wich I just need to compare the inputs on the textboxes to the defined indexes on each the arraylist of each user(user[1] for the email and user[2] for the password), but when I read the file line from line, it just makes the whole arraylist into a big string like this:
"[Name,email,password,Country,State,adress,birthdate]"is there a way to read each line as an arraylist?
btw, I'm using the BufferReader and FileReader libraries
(english is not my native tongue so, if anything is not clear, please ask so I can try to clarify it)
最满意答案
到现在为止还挺好!
假设这是字符串:
String myLine = "[Name,email,password,Country,State,adress,birthdate]";你要做的第一件事是取出括号[和] :
myLine = myLine.substring(1, myLine.length() - 2);现在我们得到了这个:
Name,email,password,Country,State,adress,birthdate所以我们要拆分数据。 观察这里的分隔符是如何逗号的。 你可以这样拆分字符串:
Strings[] fragments = myLine.split(",");数组fragments包含每个数据。 例如,名称将在fragments[0] ,而地址在fragments[5] 。
这是这里的基本原则。 但是,有一些明显的问题。 例如,我认为用户的密码很可能包含逗号。 这会破坏我们的上述方法。
有很多方法可以解决这个问题,但最简单的方法可能是使用不是逗号的分隔符。
So far so good!
Suppose that this is the string:
String myLine = "[Name,email,password,Country,State,adress,birthdate]";The first thing you want to do is take out the brackets [ and ]:
myLine = myLine.substring(1, myLine.length() - 2);Now we got this:
Name,email,password,Country,State,adress,birthdateSo we gotta split the data. Observe how the separator here are commas ,. You can split the string this way:
Strings[] fragments = myLine.split(",");The array fragments contains each piece of data. For example, the name would be in fragments[0], and the address in fragments[5].
That's the basic principle here. However, there are some obvious problems. For example, I think it's quite possible that an user's password contains a comma. This would break our above method.
There are many ways to fight this, but the simplest is probably using a separator that is not a comma.
更多推荐
发布评论