Read text file using java - 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.

Related

What is the best way to store a common part of Strings in Java?

I have some very similar string like this:
String first = "differentConfig1,config1,config2,config3,config4,config5,config6,config7,config8,config9";
String second = "differentConfig2,config1,config2,config3,config4,config5,config6,config7,config8,config9";
String third = "differentConfig3,config1,config2,config3,config4,config5,config6,config7,config8,config9";
where config1 ... config9 are the same in each string, but differentConfig1, differentConfig2 and differentConfig3 are different
what is the best way to avoid duplicating config1-9 in each string?
(Note that config1-9 are around 1 line long values)
What I have now is:
private String commonConfiguration() {
return "config1,config2,config3,config4,config5,config6,config7,config8,config9"
}
and then the strings are constructed like this:
String first = "differentConfig1," + commonConfiguration();
I was thinking about using variables instead of a function, but I am afraid that a very long variable at the beginning of the function would make it less readable.
Configuration strings are better when stored in files. This is how most systems work too. Ex: Most systems like Kafka or Cassandra have configurations of loging, log file location, addresses etc in such configuration files.
So with this approach you can change these configuration strings as per a different environment as needed without impacting code.
With the use of a properties file, your input would just be a collection of key-value pairs.
firstConfig="differentConfig1,config1,config2,config3,config4,config5,config6,config7,config8,config9"
secondConfig="differentConfig2,config1,config2,config3,config4,config5,config6,config7,config8,config9"
thirdConfig="differentConfig3,config1,config2,config3,config4,config5,config6,config7,config8,config9"
I dont really suggest breaking it further, but if you are sure that they will always have the same commonPrefix, one option is to do something like this:
In your properties file,
firstConfig="differentConfig1"
secondConfig="differentConfig2"
thirdConfig="differentConfig3"
commonPrefix="config1,config2,config3....config9"
And in your code, you read these configuration string and append them. Something like this:
String c1 = Registry.getString("firstConfig")+Registry.getString("commonPrefix")
String c2 = Registry.getString("secondConfig")+Registry.getString("commonPrefix")
String c3 = Registry.getString("thirdConfig")+Registry.getString("commonPrefix")
Note: Properties file just a file that is present in your java project that holds the information of the configurations as a key-value pair.

Which method I can use in Java for configuration file?

Which method I can use in Java for configuration files, to read and write specific lines and strings? For example (config.ini):
mysql_host: localhost
mysql_user: user
or
mysql_host = localhost
mysql_user = user
You can use ini4j library.
Ini ini = new Ini(new File(filename));
java.util.prefs.Preferences prefs = new IniPreferences(ini);
And then you can go ahead fetch nodes with prefs.node("mysql_host").
Have a look at Java Properties:
Properties are configuration values managed as key/value pairs. In
each pair, the key and value are both String values. The key
identifies, and is used to retrieve, the value, much as a variable
name is used to retrieve the variable's value. For example, an
application capable of downloading files might use a property named
"download.lastDirectory" to keep track of the directory used for the
last download.
To manage properties, create instances of java.util.Properties. This
class provides methods for the following:
loading key/value pairs into a Properties object from a stream,
retrieving a value from its key,
listing the keys and their values,
enumerating over the keys,
and saving the properties to a stream.
You can load properties files with
Properties applicationProps = new Properties();
try (FileInputStream in = new FileInputStream("appProperties")) {
applicationProps.load(in);
}
and store them with
try (FileOutputStream out = new FileOutputStream("appProperties")) {
applicationProps.store(out, "---No Comment---");
}

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/

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

Categories

Resources