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

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?

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.

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();

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("\\|"));

Need help in WildcardFileFilter in java

I have to separate out those files from a folder which matches one of the given pattern. I have an array of strings which contains these patterns. And I am passing this array as argument into WildCardFilter so that I can separate out thse files which matches the given pattern in the array. My code is given below.
String pat1="DailyExistingBusinessReport_*";
String pat2="*DailyNewExistingBusinessReport_.csv";
String pat3="*_EOD_PNL_Explained.*";
String pat4="ABC*XYZ.csv";
String str[]=new String[]{pat1,pat2,pat3,pat4};
FileFilter fileFilter = new WildcardFileFilter(str);
File dir = new File("\\C:\\Users\\ABC\\Desktop\\Myfiles");
File[] files = dir.listFiles(fileFilter);
for(File f :files){
System.out.println(f);
}
This prints out the name of files which matches the patterns given in array. But now my requirement is that alongwith each file name, I want the exact name of pattern to which this file matched. Any idea what code should I add further to get pattern name alongwith file name.
I've checked the API and don't see the way to do that with the FileFilter.
I suggest creating a list of filters and apply them one by one:
List<FileFilter> filters = new ArrayList<FileFilter>();
filters.add(new WildCardFileFilter("DailyExistingBusinessReport_*");
filters.add(new WildCardFileFilter("*DailyNewExistingBusinessReport_.csv");
filters.add(new WildCardFileFilter("*_EOD_PNL_Explained.*");
filters.add(new WildCardFileFilter("ABC*XYZ.csv");
File dir = new File("\\C:\\Users\\ABC\\Desktop\\Myfiles");
Map<FileFilter, List<File>> filemap = new HashMap<FileFilter, List<File>>();
for (File file: dir.listFiles()){
for(FileFilter filter: filters){
if(filter.accept(file)){
if(!filemap.containsKey(filter)){
filemap.put(filter, new ArrayList<File>());
}
filemap.get(filter).add(file);
}
}
}
After that, you should have a map which contain filters and lists of files for which the filter apply.
I don't have IDE by hand, so there may be some small mistakes.

Categories