Java: Read Line From File Based on Start of Line - java

I know how to read from file using Java. What I want to do is read a specific line which starts with specific text.
What I plan on doing is storing certain program settings in a txt file so I can retrieve them quickly when I exit/restart program.
For example, the file may look something like this:
First Name: John
Last Name: Smith
Email: JohnSmith#gmail.com
Password: 123456789
The : would be the delimiter and in the program I want to be able to retrieve specific values based on the "key" (such as "First Name", "Last Name" and so on).
I know I could store it to DB but I want to write it quickly to test my program without going through hassle of writing it to DB.

Have a look at java.util.Properties. It does everything you ask for here, including parsing the file.
example code:
File file = new File("myprops.txt");
Properties properties = new Properties();
try (InputStream in = new FileInputStream (file)) {
properties.load (in);
}
String myValue = (String) properties.get("myKey");
System.out.println (myValue);
Note: if you want to use a space in your property key, you have to escape it. For example:
First\ Name: Stef
Here is documentation about the syntax of the properties file.

What I want to do is read a specific line which starts with specific text.
Read from the start of the file, skipping all the lines you don't need. There is no simpler way. You can index you file for fast access, but you have scan the file at least once.

You can use Properties to retrieve both key and value from file.
Reading data from text file using Properties class
File file = new File("text.txt");
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fileInput);
fileInput.close();
Enumeration enuKeys = properties.keys();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = properties.getProperty(key);//with specific key
System.out.println(key + ": " + value);//both key and value
}
You can retrieve specific value based on the key.
System.out.println(properties.getProperty("Password"));//with specific key

With Java 8, you can also read your file into a map this way:
Map<String, String> propertiesMap = Files.lines(Paths.get("test.txt")) // read in to Stream<String>
.map(x -> x.split(":\\s+")) // split to Stream<String[]>
.filter(x->x.length==2) // only accept values which consist of two values
.collect(Collectors.toMap(x -> x[0], x -> x[1])); // create map. first element or array is key, second is value

Related

best way to store data in Java like pickle

Basically, I just want to save two integeres into a File, so that i can reuse them the next time the programm starts. Id like to do it like pickle in python, beacuse writing it just into a txt file is cumbersome. I have read some articles and other questions wehere they say I should use Java serializatio or XML or JSON, but Im not sure wheter that is the right thing in my case. Id like to use the easiest way.
thank you very much in advance for trying to solve my problem! <3
You could use serialization, XML or JSON (usually with additional libraties). An easy way to store configuration data in files is by using Java property files which are supported by the JRE without any additional dependencies. Property files are text files and have a simple key=value syntax, see below. To write two values to a property file you can do
String prop1 = "foo";
String prop2 = "bar";
try (OutputStream output = new FileOutputStream("config.properties")) {
Properties prop = new Properties();
// set the properties value
prop.setProperty("prop1", prop1);
prop.setProperty("prop2", prop2);
// save properties to project root folder
prop.store(output, "my app's config file");
} catch (IOException io) {
io.printStackTrace();
// TODO: improve error handling
}
which should give you something like
#my app's config file
#Sat Feb 29 12:29:27 CET 2020
prop2=bar
prop1=foo
And to load it:
try (InputStream input = new FileInputStream("config.properties")) {
Properties prop = new Properties();
// load a properties file
prop.load(input);
// get the property value and print it out
String prop1 = prop.getProperty("prop1");
String prop2 = prop.getProperty("prop2");
System.out.println("prop1 = " + prop1);
System.out.println("prop2 = " + prop2);
} catch (IOException ex) {
ex.printStackTrace();
// TODO: improve error handling
}
For integer values you would need some type conversion, e.g. the first two lines would be
String prop1 = Integer.toString(23);
String prop2 = Integer.toString(42);
and reading the properties then becomes
int prop1 = Integer.parseInt(prop.getProperty("prop1"));
int prop2 = Integer.parseInt(prop.getProperty("prop2"));
This solution does not scale well in case the number of properties increases or there are frequent changes. For a more generic procedure, see this post: Get int, float, boolean and string from Properties

How to modify a given String (from CSV)

I need to write a program for a project at university which should cut some specific parts out of a given CSV File. I've started already but I don't know how to keep only the content (sentence and vote values) or min. to remove the date part.
PARENT,"Lorem ipsum...","3","0","Town","09:17, 29/11/2016"
REPLY,"Loren ipsum...”,"2","0","Town","09:18, 29/11/2016"
After the program ran I want to have it like this:
Lorem ipsum... (String) 3 (int) 0 (int)
Loren ipsum... (String) 2 (int) 0 (int)
I have no problem with writing a parser (read in, remove separators) but I don't know how realize this thing.
You can create your own data structure that contains a string, and two integers and then do the following while reading from the csv file. Only include the stuff you want from the csv based on the column number which is the index of the String array returned by the split() method.
Scanner reader = new Scanner(new File("path to your CSV File"));
ArrayList<DataStructure> csvData = new ArrayList<>();
while(reader.hasNextLine())
{
String[] csvLine = reader.nextLine().split(",");
DataStructure data = new DataStructure(
csvLine[1],
Integer.parseInt(csvLine[2]),
Integer.parseInt(csvLine[3]));
csvData.add(data);
}

Csv: search for String and replace with another string

I have a .csv file that contains:
scenario, custom, master_data
1, ${CUSTOM}, A_1
I have a string:
a, b, c
and I want to replace 'custom' with 'a, b, c'. How can I do that and save to the existing .csv file?
Probably the easiest way is to read in one file and output to another file as you go, modifying it on a per-line basis
You could try something with tokenizers, this may not be completely correct for your output/input, but you can adapt it to your CSV file formatting
BufferedReader reader = new BufferedReader(new FileReader("input.csv"));
BufferedWriter writer = new BufferedWriter(new FileWriter("output.csv"));
String custom = "custom";
String replace = "a, b, c";
for(String line = reader.readLine(); line != null; line = reader.readLine())
{
String output = "";
StringTokenizer tokenizer = new StringTokenizer(line, ",");
for(String token = tokenizer.nextToken(); tokenizer.hasMoreTokens(); token = tokenizer.nextToken())
if(token.equals(custom)
output = "," + replace;
else
output = "," + token;
}
readInventory.close();
If this is for a one off thing, it also has the benefit of not having to research regular expressions (which are quite powerful and useful, good to know, but maybe for a later date?)
Have a look at Can you recommend a Java library for reading (and possibly writing) CSV files?
And once the values have been read, search for strings / value that start with ${ and end with }. Use Java Regular Expressions like \$\{(\w)\}. Then use some map for looking up the found key, and the related value. Java Properties would be a good candidate.
Then write a new csv file.
Since your replacement string is quite unique you can do it quickly without complicated parsing by just reading your file into a buffer, and then converting that buffer into a string. Replace all occurrences of the text you wish to replace with your target text. Then convert the string to a buffer and write that back to the file...
Pattern.quote is required because your string is a regular expression. If you don't quote it you may run into unexpected results.
Also it's generally not smart to overwrite your source file. Best is to create a new file then delete the old and rename the new to the old. Any error halfway will then not delete all your data.
final Path yourPath = Paths.get("Your path");
byte[] buff = Files.readAllBytes(yourPath);
String s = new String(buff, Charset.defaultCharset());
s = s.replaceAll(Pattern.quote("${CUSTOM}"), "a, b, c");
Files.write(yourPath, s.getBytes());

Reading in data from a file and using it to create a new object

I have a class called Name like so.
public Name (String first, String last)
This is a text file that contains names, its filename is "names.txt".
John Doe
Jane Doe
The file called "names.txt" is read in like so.
File read = new File ("names.txt");
Scanner in = new Scanner(read);
I want to know how to automatically create a new name object using the first word (John) as the first parameter and the second word (Doe) as the second parameter.
How do I do this?
Ok, I'll help you out. The line you want is
Name n = new Name(in.next(), in.next());
It's that simple, although this is not a particularly robust way.
read the file using scanner and include the split portion
//while(scanner) iterate the scanner upto end of the file read every line
{
String[] splitResult = input.split(" ");
firstName = splitResult[0];
lastName = splitResult[1];
storeMethod(firstName,lastName); // use this method to store the first name and last name
}

need to extract key from properties file

see i have one PROPERTIES File now i have to write a program for extraction of all keys from that file
1000012001 = Title
1000012002 = Status
1000012003 = Start Date
1000012004 = End Date
1000012005 = Date
1000012006 = Name
1000012007 = Description
1000012008 = Sr No
1000012009 = Action
1000012010 = Add
1000012011 = COMPASS Alerts
1000012012 = All
1000012013 = Apply
like in given example i have to extract keys like 100012001---100012013 from that file keys may not be in one sequence and keys need to store in hashmap or arraylist
so please help me
Properties props = new Properties();
props.load(in); // create input stream for your file.
// from now you have Properties object with your data.
// since properties extends Hashtable the task is done.
// if you still need keys in list, say
List<Object> keys = new ArrayList<Object>(props.keySet());
I hope this helps although the question does not seem very clear for me.
You can use java.util.Properties which extends Hashtable.
Properties props=new java.util.Properties();
props.load(inputStream);

Categories

Resources