Reading specific parts of a text file using Scanner class in Java - 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/

Related

Read text file using java

I have a text file contain two data in two line
admin
temp123
I want to read the text file and store this text to two string for further use.
like,
String username = "admin";
String password = "temp123";
Can any one help me?
Simple google search would have done the job. Check these link:
- https://www.geeksforgeeks.org/different-ways-reading-text-file-java/
- https://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
It looks like you are trying to use this for login credentials for something in your application. I would suggest that you look into working with .properties files to get your values, as in the end the java Properties class will handle reading the file and iterating through the key, value pairs it contains.
Example text file:
username=myUser
password=myC0mpLicat3dPa$$W0rd
Java Code:
Properties prop = new Properties();
prop.load(new FileInputStream("myTextFileHere.properties"));
String username = prop.getProperty("username"); // assigned value of "myUser"
String password = prop.getProperty("password"); // assigned value of "myC0mpLicat3dPa$$W0rd"
This will be much simpler than iterating the file, and I imagine more efficient when you decide to work with reading more than two variables in the future.

Modify JSON database values with java in eclipse

I want to use eclipse and java to make a program that can parse json files in java only.
For example, I want to change a value in JSON to another value every second.
I know the jsonparse function in javascript, but to carry it over through scriptengine alone seems like a bad solution.
I also know that I can use Apache IO to read a file to string and then edit the string and read the file back, but it doesn't seem efficient.
Is there an effective way to modify values in a JSON.php file?
Here is a JSON.php file that I have.
[{"color": "red waves-effect waves-light", "value": "0", "activator": "null"}]
Here is a part of my java program that does the text editing.
String attentionVs = "" + attentionV;
File fileattentionV = new File("attentionV.php");
String fileContext2 = FileUtils.readFileToString(fileattentionV);
fileContext2 = attentionVs;
FileUtils.write(fileattentionV, fileContext2);
String meditationVs = "" + meditationV;
File filemeditationV = new File("meditationV.php");
fileContext2 = FileUtils.readFileToString(filemeditationV);
fileContext2 = meditationVs;
FileUtils.write(filemeditationV, fileContext2);
Thanks for your help!
Going on just the first sentence where you say you want to parse a JSON file in Java, have you seen this post How to parse JSON in Java

Java/Bukkit (Minecraft) - If file contains playername then check password which is stored in same line after a ":" and do something

this is my first question and I hope you can help me. I'm coding a register/login plugin for Bukkit in Java. Now when the player joins my server I'd like that he log-ins. My plugin must check if the password which the player provided is right. This is the code which I have done so far.
The problem is, that I have no idea, how to do this. Can someone explain how to do this (maybe only in words)?
String currln;
br = new BufferedReader(new FileReader("/plugins/LobbyLogin/passwd.crypt"));
while ((currln = br.readLine()) != null) {
password = currln;
}
String password = null;
String[] select = password.split(":");
String username = select[0];
String readed_pwd = select[1];
String alldata = username+readed_pwd;
P.S.: The password of the user is saved in a file called "passwd.crypt" which I have created. Here's a example string from it.
ExampleUser:cGFzc3dvcmQ=
The password is stored encrypted.
I suggest using the YAML built-in library provided by Bukkit to store passwords and associate them with a user. Then you can use a simple FileConfiguration#getString(String) to get the password associated with the user.
I don't know the exact implementation of SnakeYAML, but I assume it stores a line number table to reference the Node stored at the position to get the object, instead of a BufferedReader to read every line. This means a performance gain for large files.
And, two things: Unless you have hardware security issues, why encrypt passwords? And, I don't IO during runtime, hold reference to initial value at plugin startup in a collection, it's faster than disk read from file.

Reading specific llines from a file each one representing a different data type and variable in Java

I've been researching on the web how to go about this and what class is best to use for file parsing ect.
I've been programming In java for awhile now and parsing files and writing to them has always been one of weakest points literally I just don't understand It.
Specifically I have a file named
jihoon.txt
its contents are this
username = ji
password = kim106
id = 0
i want to store ji into a string variable, and kim106 into a string variable and id into an int variable while disregarding "username = "
ect. Could someone please help thanks in advance :).
A good way would be to use the file as a Property. This way you can load everything the way you want.
You would load you file as such :
properties.load(new FileInputStream("path/jihoon.txt"));
Then you can access your data as such :
String value = properties.getProperty(key);
Knowing what the key is for your values you can have something like this (according to your example in the question) :
int id = Integer.parseInt(properties.getProperty("id")).intValue();
String username = properties.getProperty("username");
String password = properties.getProperty("password");
Then this way you don't have to worry about the order of your file.
See also
How to use Java property files?
Why variables? How about a HashMap?
HashMap<String, String> keyValueMap = new HashMap<>();
and then feed the pairs after splitting at = there.
A properties file would be best for these kinds of operations
Example

Updating TableView using a CSV

Much like this question, I am trying to update a TableView in JavaFX. I have adopted the solution using DataFX.
My code :
File file = new File(path);
if(file.exists() && file.canRead()) {
DataSourceReader dsr1 = new FileSource(file);
String[] columnsArray = {"firstName", "lastName"};
CSVDataSource ds1 = new CSVDataSource(dsr1, columnsArray);
System.out.println("CSV : " + ds1.getData().size()); // outputs 0
//Below is commented out since I don't have data : source of the error
//tblAthleteList.setItems(ds1.getData());
//tblAthleteList.getColumns().addAll(ds1.getColumns());
}
Here is a view of my test .csv file :
firstName, lastName
first, last
test, tester
I am using JavaFX 2, DataFX 1.0 and building in e(fx)clipse
Edit
Have changed the code a bit to use the FileSource(File f) constructor to see if this changes anything. Turns out I am trying to print something from the CSVDataSource and I always get a NullPointerException. Therefore assumming that the CSVDataSource doesn't get any data. From examples I can find this is being done correctly. I can read the file using a simple BufferedReader and a loop.
Edit 2
Edited the question... I am now specifying that the error is in the fact that no data gets pulled into the CSVDataSource from the .csv file. The line ds1.getData().size() returns 0. Posted a very simple .csv file I am using. EOL consists of CR + LF and edited in Notepad++ (no Excel superfluous characters).
make sure column names in columnsArray are exactly equal to column names in CSV file (case sensitive).
i got the similar exception when i put my column name as year in code but in my csv file its Year.
Update According to Edit in Question :
remove space between , and lastName in file or put " lastName" as column name in code :)

Categories

Resources