Adding String ArrayList into properties File java? - 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("\\|"));

Related

Load an ArrayList with nested ArrayLists from a file using Java

I have an arraylist like ArrayList<ArrayList<String>>. I have saved my main ArrayList in a text file by using the following code.
ArrayList<ArrayList<String>> ar2 = new ArrayList<>();
FileWriter writer = new FileWriter("path/to/the/text/file");
for(ArrayList<String> str: ar2) {
writer.write(str + System.lineSeparator());
}
writer.close();
Now, I want to load the saved data from the file to the same ArrayList ar2 in every new run. I tried several methods but the nested arraylists are loaded as Strings. How can I overcome from this issue?
Read the file contents, split by line separator and then remove the brackets and split again to get the list items. Something like
File file = new File("path/to/the/text/file");
FileReader reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
String fileContent = new String(chars);
ArrayList<ArrayList<String>> readList = new ArrayList<>();
String[] splittedArr = fileContent.split(System.lineSeparator());
for(String list : splittedArr) {
list = list.replace("[", "").replace("]", ""); //removing brackets as the file will have list as [a, b, c]
List<String> asList = Arrays.asList(list.split(", "));//splitting the elements by comma and space
readList.add(new ArrayList<>(asList));
}
reader.close();
Either you can parse the string and convert it to an Array using iteration or you can use a library that will do it for you.
I would recommend using Jackson, you can find an easy tutorial here.

using java.nio.file adding the arraylist to the file

What method can be used to add arraylist to the file using java.nio.file ?
Previously I could be using
List<String> outputData = new ArrayList<String>();
//Output arraylist containing concatenated data
writeLines(File outputFile,outputData); //The data is written to file
now if i want to utilize nio library what do i do?
Path outputFile= Paths.get("outputFile");
List<String> outputData = new ArrayList<String>();
//???How to put the list in the file?

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.

Write List into .csv file

I have a list and want to write the data into .csv file.
This is an example how my list looks like:
Each element contains the values from a database table. I deleted the information here. For example List[0] contains id = 1, name = Test, date = 02.02.2016 etc.
This is my code so far, but I have no Idea how to continue.
List<String> lines = Arrays.asList("ColumnHeader", "ColumnHeader", " ColumnHeader","ColumnHeader","ColumnHeader");
Path file = Paths.get(test.csv");
Files.write(file, lines, Charset.forName("Windows-1252"));
Take a look at OpenCSV. This library contains tools for writing List and array objects to csv files, and even database result sets can be written directly to a file.
CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), '#');
java.sql.ResultSet myResultSet = ....
writer.writeAll(myResultSet, includeHeaders);
writer.close();

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

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.

Categories