简体   繁体   中英

Reading specific parts of a text file using Scanner class in Java

I have gone through most of the questions related to reading a Text file using the Scanner class here, but I still don't understand how I parse the following text into different variables and then replace that text with the changed variable values. Here is the text :

## UserID1.Credentials : 
[Username] = {default}
[Password] = {passwordforadmin}
[AccType] = {Admin.FirstDefault}
[AccessLevel] = {1}
##

Now, I need the above text parsed into the following variables, where :

int UserID = 1;
String Username = "default";
String Password = "passwordforadmin";
String AccType = "Admin";
String AccUnderType = "FirstDefault";
int AccessLevel = 1;

The method I am using to read the text file is :

String content = new Scanner(new File("D:/EncryptedCredentials.txt")).useDelimiter("\\Z").next();

Where content is the String which reads the text file (D:/EncryptedCredentials.txt) and the delimiter '\\Z' is used. (I need to load the whole text file into a String, because it would be continuously modified by the program, and further details should be added automatically, like if the User logged in at a specific time, say 11:00 AM, and logged out at 3:00 PM, and used A,B and C features, then the above text should be modified to :

## UserID1.Credentials : 
[Username] = {default}
[Password] = {passwordforadmin}
[AccType] = {Admin.FirstDefault}
[AccessLevel] = {1}
[LastLogInTime] = {1100}
[LastLogOutTime] = {1500}
[TotalTimeSpent] = {0400}
[FeaturesUsed] = {A,B,C}
##

How do I go about this reading and writing to a text file ? Another question is, since anyone can evidently see I am doing a login system, I need to know how encryption can be implemented into the text file so that people can access the contents of the text file only through the program. The text can be changed, of course. All I need is for the program to read it and store specific information in the appropriate variables, and then to write it back to the encrypted text file.

So, in all, what I need to know is :

How to read only specific parts of a text file loaded onto a String ? How to modify those parts (including adding text that wasn't present before) and write them again to the text file ? How to do the above steps while implementing encryption into the text file ?

Please explain them to me, because I don't have much knowledge about this. Thanks in advance.

Note : I'm still a beginner in Java, and I have no idea of anything more than Scanner classes, Arrays, loops, etc. and some random stuff. Please help me out.

I suggest simpler approach by using properties file. Here is a link to an example: http://www.mkyong.com/java/java-properties-file-examples/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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