【问题标题】:How to pull information from a text document then print it out如何从文本文档中提取信息然后打印出来
【发布时间】:2019-09-18 14:15:45
【问题描述】:

我想问一下如何从 txt 文档中提取信息(我的 txt 文档包含类似

巴金斯,比尔博,,是的

巴金斯,弗罗多,,N

我尝试了一些东西。我还想知道如何将每个部分存储在变量中,以便我可以在字符串生成器/use.trim 中编辑它们以消除空格。

这是我尝试过的:

import java.io.FileNotFoundException;     
import java.lang.SecurityException;       
import java.util.Formatter;               
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;  
import java.util.Scanner;



/**
 *
 * 
 */
public class pullingEmails {
  public static void main(String[] args) {
      Scanner input = new Scanner(System.in);

     // open contacts.txt, output data to the file then close contacts.txt
     try (Formatter output = new Formatter("contacts.txt")) {
         while (input.hasNext()) { // loop until end-of-file indicator
            try {
               // output new record to file; assumes valid input
               output.format("%s %s %s %s", input.next(),  
              input.next(), input.next(), input.next());
            } 
            catch (NoSuchElementException elementException) {
           System.err.println("No email address: " );
           input.nextLine(); // discard input so user can try again
        } 




     }
  }
  catch (SecurityException | FileNotFoundException | 
     FormatterClosedException e) {
     e.printStackTrace();
     System.exit(1); // terminate the program
      } 
   } 
}

我不是最擅长 Java,这是一个新概念。我基本上需要它来打印文件中的内容

Gamgee,Samwise,donleaveimsamwise@theShire.com,Y

                // every email has < > around them I will remove once i know how to pull the information correctly)

Baggins,Drogo,drogobagginstheshire.com,N

Erling,,erling@theshire.com,Y

Fortinbrass, Took,,Y

if 异常语句示例(不是 100% 确定如何格式化):

if No email address
system.err.println("No email address: Chester, Steve,, N");

if (!email.contains("@"))
system.err.println("Invalid email address: "<simon#gmail.com>". Missing @ symbol.");

if invalid character //(only capital, lowercase, and @ symbol aloud)
system.err.println ("Invalid character '%' at position 4 in last name: "Robe%tson")

我当前的输出不起作用。我试图按照我的一个示例进行操作,但该示例首先要求将信息放入文件中。不确定如何读取文件中的内容,将其打印出来,然后能够将每个部分存储在变量中,如 firstName、lastName、Email、Sub 等。

【问题讨论】:

    标签: java


    【解决方案1】:

    请参阅question,了解如何在 Java 中读取文件。 由于每一行似乎都由逗号分隔的值组成,您可以使用 split 将单个值作为数组获取。使用streams(或for-each 循环),您可以清除这些值,例如使用strip 删除空格,使用replaceAll 删除括号。 要将数组转换回一行,您可以使用join。您可以使用String 或更好的StringBuilder 收集行。

    这是一个例子:

    StringBuilder sb = new StringBuilder();
    try {
        Files.lines(Path.of("test.txt")).forEach(x -> {
            String[] split = x.split(",");
            split = stream(split).map(y -> {
                String cleaned = y.strip().replaceAll(">$|^<", "").strip();
                return cleaned;
            }).toArray(String[]::new);
            String email = split[2];
            // TODO: other data
            if (email.isBlank()) {
                System.err.println("No email address");
            }
            // TODO: other checks
            sb.append(String.join(", ", split));
            sb.append(System.lineSeparator());
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    String result = sb.toString();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-14
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多