How to get the data after "=" sign from a txt file? - java

I have a program, in Java, that will save data to a .txt file and save it like:
intdata=2
stringdata=hello
How will I read the data from the text file and specify the value I need. Lets say I want the intdata value, it would return the part after the equals. How do I only return the part after the equals?

If you don't care about the key it's attached to: use String.split.
Scanner scan = new Scanner(new File("file.txt"));
String value = scan.nextLine().split("=")[1];
If you do care about the key it's attached to: use String.split in conjunction with a Map.
Scanner scan = new Scanner(new File("file.txt"));
Map<String, String> values = new HashMap<>();
while(scan.hasNextLine()) {
String[] line = scan.nextLine().split("=");
values.put(line[0], line[1]);
}
Alternatively, if it's a proper .properties file, you could elect to use Properties instead:
Properties propertiesFile = new Properties();
propertiesFile.load(new FileInputStream("file.txt"));
// use it like a regular Properties object now.

Related

How to store specific Key-Value Pairs from properties file

I want to store the key values pair in java from the config.properties file. Problem is it has some other which in dont want to store in array or hashmap.Below is my config.properties file. One thing the line must start with #usergroup and end of line should be End_TT_Executive as described in the file
#Usergroup
TT_Executive
#Tilename
KPI
#No of Submenu=3
#Submenu_1
OPs_KPI=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Submenu_2
Ontime_OnBudget=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#submenu_3
Ops_KPI_Cloud=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Tilename
Alerting Dashboard
#No of submenu=0
Alerting_Dashboard=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Tilename
FTE_Dashboard
#No of submenu=3
#Submenu_1
FTE_Market_Sector_TT_Executive= https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#submenu_2
FTE_Account_TT_Executive= http://tntanalytics1.sl1430087.sl.dst.ibm.com/ibmcognos/bi/?pathRef=.public_folders%2FP=false
#Submenu_3
FTE_Laborpool_TT_Executive= https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
#Tilename
PCR
#No of Submenu=0
PCR=https://tntanalytics3.sl1430087.sl.dst.ibm.com:8443/CAP-T/res/html/underprogress.html
End_TT_Executive
How can I do this? The key value pair are with URL only rest is some title for understanding.
Suppose your config.properties is like:
p1=abc
p2=def
p3=zxc
p4=eva
and you want to load p1 and p2 to map.
You can load all properties into Properties instance with:
InputStream inputStream = null;
try
{
inputStream = new BufferedInputStream(new FileInputStream("config.properties"));
Properties properties = new Properties();
properties.load(new InputStreamReader(inputStream, "UTF-8")); // load all properties in config.properties file
}
catch ( IOException e )
{
e.printStackTrace();
}
finally
{
inputStream.close();
}
Then you create a map:
Map<String, String> propertyMap = new HashMap<>();
You also need a String[] to store all properties which you want to load to propertyMap.
String[] wantedProperties = new String[]{"p1", "p2"};
Then you write a for loop to load the properties you wanted:
for (String property : wantedProperties) {
propertyMap.put(property, properties.getProperty(property));
}
Now propertyMap is what you want.
If you want to store to List:
List<String> propertyList = new ArrayList<>();
for (String property : wantedProperties) {
propertyList.add(properties.getProperty(property));
}
This is the way to save to list. It'll help you more if you find the solution yourself.

Best way to populate a user defined object using the values of string array

I am reading two different csv files and populating data into two different objects. I am splitting each line of csv file based on regex(regex is different for two csv files) and populating the object using each data of that array which is obtained by splitting each line using regex as shown below:
public static <T> List<T> readCsv(String filePath, String type) {
List<T> list = new ArrayList<T>();
try {
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
list = bufferedReader.lines().skip(1).map(line -> {
T obj = null;
String[] data = null;
if (type.equalsIgnoreCase("Student")) {
data = line.split(",");
ABC abc = new ABC();
abc.setName(data[0]);
abc.setRollNo(data[1]);
abc.setMobileNo(data[2]);
obj = (T)abc;
} else if (type.equalsIgnoreCase("Employee")) {
data = line.split("\\|");
XYZ xyz = new XYZ();s
xyz.setName(Integer.parseInt(data[0]));
xyz.setCity(data[1]);
xyz.setEmployer(data[2]);
xyz.setDesignation(data[3]);
obj = (T)xyz;
}
return obj;
}).collect(Collectors.toList());} catch(Exception e) {
}}
csv files are as below:
i. csv file to populate ABC object:
Name,rollNo,mobileNo
Test1,1000,8888888888
Test2,1001,9999999990
ii. csv file to populate XYZ object
Name|City|Employer|Designation
Test1|City1|Emp1|SSE
Test2|City2|Emp2|
The issue is there can be a missing data for any of the above columns in the csv file as shown in the second csv file. In that case, I will get ArrayIndexOutOfBounds exception.
Can anyone let me know what is the best way to populate the object using the data of the string array?
Thanks in advance.
In addition to the other mistakes you made and that were pointed out to you in the comments your actual problem is caused by line.split("\\|") calling line.split("\\|", 0) which discards the trailing empty String. You need to call it with line.split("\\|", -1) instead and it will work.
The problem appears to be that one or more of the last values on any given CSV line may be empty. In that case, you run into the fact that String.split(String) suppresses trailing empty strings.
Supposing that you can rely on all the fields in fact being present, even if empty, you can simply use the two-arg form of split():
data = line.split(",", -1);
You can find details in that method's API docs.
If you cannot be confident that the fields will be present at all, then you can force them to be by adding delimiters to the end of the input string:
data = (line + ",,").split(",", -1);
Since you only use the first values few values, any extra trailing values introduced by the extra delimiters would be ignored.

Adding String ArrayList into properties File java?

Is it possible to store a String ArrayList into a properties file and then read and modify the list in a simple way?
I think i will need to run example:
Properties p = new Properties();
File f = new File("MyText.txt");
FileInputStream in = new FileInputStream(f,"");
p.load(in);
ArrayList<String> list = p.getProperty("list");
<-- Modify the list and then open a OutputStream and save the p object again ?
Is this possible to manage easily in Java?
You can use a delimiter, say '|', to join the Strings in your ArrayList. When saving your list, use this code (String.join() needs Java 8):
String listAsString = String.join("|", list);
properties.put("list", listAsString);
When retrieving the list, do this:
List<String> list = Arrays.asList(properties.get("list").toString().split("\\|"));

How to access values of a line, while reading in a text file in Java

I am trying to load in two files at the same time but also access the first gps1 file. I want to access the gps1 file line-by-line and depending on the sentence type which I will explain later I want to do different stuff with that line and then move to the next line.
Basically gps1 for example has multiple lines but each line falls under a couple of catagories all starting with $GPS(then other characters). Some of these types have a time stamp which I need to collect and some types do not have a time stamp.
File gps1File = new File(gpsFile1);
File gps2File = new File(gpsFile2);
FileReader filegps1 = new FileReader(gpsFile1);
FileReader filegps2 = new FileReader(gpsFile2);
BufferedReader buffer1 = new BufferedReader(filegps1);
BufferedReader buffer2 = new BufferedReader(filegps2);
String gps1;
String gps2;
while ((gps1 = buffer1.readLine()) != null) {
The gps1 data file is as follows
$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A
$GPRMC,151018.000,A,5225.9627,N,00401.1624,W,0.11,104.71,210214,,*14
$GPGGA,151019.000,5225.9627,N,00401.1624,W,1,09,1.0,38.9,M,51.1,M,,0000*72
$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A
Thanks
I don't really understand the problem you are facing but anyway, if you want to get your lines content you can use a StringTokenizer
StringTokenizer st = new StringTokenizer(gps1, ",");
And then access the data one by one
while(st.hasMoreToken)
String s = st.nextToken();
EDIT:
NB: the first token will be your "$GPXXX" attribute

read/write files in Java

How can I read a file easily in Java if I have following file format:
a|dip
a|dop
c|nap
a|dip
b|dop
b|sip
a|tang
c|dig
c|nap
I want to get all words that belongs to "a", "b", and "c". What data structure I can use to read and store this information?
You can also suggest some good file formats (two column) that is easy to read/write in Java.
I know some of you may be thinking that what is the real problem that I want to solve, I have some complex employee related data. Current (poor) system generate some files and I am trying to process them to add them in database. The current files' format is bit complex (private), I cannot copy past here.
If you can use Google Guava (http://code.google.com/p/guava-libraries/) then you'll get a few handy classes (you can use some or all of these):
com.google.common.io.Files
com.google.common.io.LineProcessor<T>
com.google.common.base.Charsets
com.google.common.collect.Multimap<K,V>
com.google.common.collect.ArrayListMultimap<K,V>
For example you could write:
LineProcessor<Multimap<String, String>> processor =
new LineProcessor<Multimap<String, String>>() {
Multimap<String, String> processed = ArrayListMultimap.create();
public boolean processLine(String line) {
String parts[] = line.split("\\|", 2); // 2 keeps any | in the rest of the line
processed.put(parts[0], parts[1]);
return true; // keep going
}
public Multimap<String, String> getResult() {
return processed;
}
};
Multimap<String, String> result = Files.readLines(
new File("filename.txt"), Charsets.UTF_8, processor);
You can use Scanner to read the text file one line at a time and then you can use String.split("\\|") to separate the parts on that line. For storing the information, a Map<String,List<String>> might work.
I'd use this data structure:
Map<String, List<String>> map = new HashMap<String, List<String>>();
And parse the file like this:
File file = new File("words.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
String next = scanner.next();
String[] parts = next.split("\\|");
String group = parts[0];
String word = parts[1];
List<String> list = map.get(group);
if (list == null) {
list = new ArrayList<String>();
map.put(group, list);
}
list.add(word);
}
So you could get the list of words for "a" like so:
for (String word : map.get("a")) {
System.out.println(word);
}

Categories