简体   繁体   English

想要每 2 个新行分隔字符串并将其添加到数组

[英]Want to seperate string every 2 new lines and add it to array

I have.txt file which I convert to string.我有.txt 文件,我将其转换为字符串。 I want to store every 2 new lines starting from the 1 all the way to the last number.我想存储从 1 一直到最后一个数字的每 2 行新行。

name.txt file: name.txt 文件:

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:我想将这些内容存储在一个数组列表中,每 2 行分隔一次:

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:很公平,我有这段代码,但最后一行拆分并没有真正起作用,因为对于这个文件,我必须跳过第一行,然后一次拆分 rest 2 行,这使它不起作用:

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

There are several ways to do this.有几种方法可以做到这一点。 Here is one using the Scanner class to read the file line by line.这是一个使用扫描仪 class 逐行读取文件的方法。 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.此示例中使用的策略是丢弃第一行,然后使用 while 循环遍历文件的 rest。

This example assumes the file exists in the resources since the OP appears to be loading a resource file.此示例假定文件存在于资源中,因为 OP 似乎正在加载资源文件。

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.并根据问题使用名为“people.txt”的文本文件进行简单测试。

@Test
void shouldLoadPeople() throws IOException, URISyntaxException {
    List<String> people = extractPeople("people.txt");
    assertEquals(5, people.size());
}

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.由于确实似乎要读取的文件位于资源目录中,因此以下可运行代码将读取 IDE 或分布式 JAR 文件中的文件。 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:运行上述代码时,控制台 Window 中应显示以下内容,提供Users.txt文件:

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 >

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM