I have .txt file which I convert to string. I want to store every 2 new lines starting from the 1 all the way to the last number.
name.txt file:
imported/names/A
1/name=Arwin
2/Age=22
3/name=AJ
4/Age = 27
5/name=Anna
6/Age = 21
7/name=Avon
8/Age = 25
9/name=Atman
10/Age = 19
I want to store these contents in a array list seperating every 2 new lines:
ArrayList = ["1/name=Arwin2/Age=22","3/name=AJ4/Age = 27","5/name=Anna
6/Age = 21","7/name=Avon8/Age = 25"9/name=Atman10/Age = 19"]
So fair I have this code but the last line splitting doesnt really work because for this file I have to skip the very first line and then split the rest 2 lines at a time which makes it not work:
File file = new File(classLoader.getResource("name.txt").getFile());
String data = FileUtils.readFileToString(file, "UTF-8");
List<String> items = Arrays.asList(data.split("\\n\\n));
CodePudding user response:
There are several ways to do this. Here is one using the Scanner class to read the file line by line. The strategy used in this example is to discard the first line and then use a while loop to iterate over the rest of the file.
This example assumes the file exists in the resources since the OP appears to be loading a resource file.
public List<String> extractPeople(String fileName) throws IOException, URISyntaxException {
List<String> people = new ArrayList<>();
URL url = getClass().getClassLoader().getResource(fileName);
if (Objects.isNull(url)) throw new IOException("Unable to load URL for file: " fileName);
// try with resources and use scanner to read file one line a time
try (Scanner scanner = new Scanner(new FileReader(new File(url.toURI())))) {
// move cursor to the second line
scanner.nextLine();
// loop through the file
while(scanner.hasNextLine()) {
// extract the line with name
String name = scanner.nextLine();
// extract the line with the age
String age = scanner.nextLine();
// concatenate name and age and add to list of results.
people.add(name.concat(age));
}
}
return people;
}
And a simple test using a text file named "people.txt" based of the question.
@Test
void shouldLoadPeople() throws IOException, URISyntaxException {
List<String> people = extractPeople("people.txt");
assertEquals(5, people.size());
}
CodePudding user response:
Just another way. As it does indeed appear that the file to read is located within a resources directory, the following runnable code will read the file in both the IDE or the distributive JAR file. The resources directory is assumed to be located within the following hierarchy:
ProjectFolder
src
resources
Users.txt
Read the comments in code:
public class ExtractDataDemo {
private final String LS = System.lineSeparator();
// Class global List to hold read in Users.
private final java.util.List<String> usersList = new java.util.ArrayList<>();
private final String resourceFile = "/resources/Users.txt";
public static void main(String[] args) {
// Started this way to avoid the need for statics.
new ExtractDataDemo().startApp(args);
}
private void startApp(String[] args) {
try {
// Read the Users.txt file
readUsers(resourceFile);
}
catch (java.io.IOException ex) {
// Display IO exceptions (if any) in Console.
System.err.println(ex);
}
// Display the people List contents in Console Window:
System.out.println(LS "Users List (as List):");
System.out.println("=====================");
for (String elements : usersList) {
System.out.println(elements);
}
System.out.println();
// Display a table style formated people List in Console:
// Header...
System.out.println("Users List (as Table):");
System.out.println("======================");
System.out.printf("%-8s %-11s %-3s%n", "Import", "Name", "Age");
System.out.println("------------------------");
// Iterate through the people List so to format contents...
for (String peeps : usersList) {
// Split list element into parts for formatting.
String[] peepParts = peeps.split("/");
System.out.printf(" %-6s %-11s %-3s%n",
peepParts[0], // Import Number
peepParts[1].split("\\s*=\\s*")[1], // Name
peepParts[2].split("\\s*=\\s*")[1]); // Age
}
System.out.println("------------------------");
System.out.println(LS "< DONE >" LS);
// DONE
}
public void readUsers(String fileName) throws java.io.IOException {
/* Clear the usersList in case it has something
already in it from a previous operation: */
usersList.clear();
/* Read from resources directory. This will work in
both the IDE and a distributive JAR file. 'Try With
Resources' is used here to suto-close file and free
resources. */
try (java.io.InputStream in = getClass().getResourceAsStream(fileName);
java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(in))) {
String line;
//Skip header line in file (don't want it this time).
line = reader.readLine();
while ((line = reader.readLine()) != null) {
// Get Import # from line (ex: "1"/name=Arwin)
String imprt = line.split("/")[0];
// Get Name from line (ex: 1/"name=Arwin")
String name = line.split("/")[1];
/* Read in the line with the age (omit the line number)
[Ex: "2/Age=22"] */
line = reader.readLine();
// Get the age from line (ex: 2/"Age=22")
String age = line.split("/")[1];
// Concatenate import number, name, and age then add to usersList.
usersList.add(imprt.concat("/").concat(name).concat("/").concat(age));
}
}
}
}
When the code above is run, the following is what should be displayed within the Console Window providing the Users.txt
file can be found:
Users List (as List):
=====================
1/name=Arwin/Age=22
3/name=AJ/Age = 27
5/name=Anna/Age = 21
7/name=Avon/Age = 25
9/name=Atman/Age = 19
Users List (as Table):
======================
Import Name Age
------------------------
1 Arwin 22
3 AJ 27
5 Anna 21
7 Avon 25
9 Atman 19
------------------------
< DONE >