【发布时间】: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