Java 如何从文本文档中提取信息,然后将其打印出来
我想问一下如何从txt文档中提取信息(我的txt文档包含 巴金斯,比尔博,Java 如何从文本文档中提取信息,然后将其打印出来,java,Java,我想问一下如何从txt文档中提取信息(我的txt文档包含 巴金斯,比尔博,,Y 巴金斯,佛罗多,,N 我尝试过一些东西。我还想知道如何将每个部分存储在变量中,这样我就可以在字符串生成器/use.trim中编辑它们,以消除空白 这就是我所尝试的: import java.io.FileNotFoundException; import java.lang.SecurityException; import java.util.Formatter;
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,这是一个新概念。我基本上需要它来打印文件中的内容
甘吉,桑怀斯,donleaveimsamwise@theShire.com,Y
// every email has < > around them I will remove once i know how to pull the information correctly)
//每封电子邮件周围都有<>信息,一旦我知道如何正确提取信息,我将删除这些信息)
巴金斯,德罗戈,德罗戈巴金森郡
二陵,,,erling@theshire.com,Y
// every email has < > around them I will remove once i know how to pull the information correctly)
福廷布拉斯
异常的if语句示例(无法100%确定如何格式化):
如果没有电子邮件地址
system.err.println(“无电子邮件地址:切斯特,史蒂夫,N”);
如果(!email.contains(“@”))
system.err.println(“无效的电子邮件地址:。缺少@symbol”);
如果无效字符//(仅大写、小写和@符号)
system.err.println(“姓氏中位置4处的无效字符“%”:“Robe%tson”)
我当前的输出不起作用。我尝试了一个例子,但这个例子要求首先在文件中输入信息。不确定如何读取文件中的内容,请打印出来,然后能够将每个部分存储在变量中,如firstName、lastName、Email、Sub等。有关如何在Java中读取文件的信息,请参见此。
由于每一行似乎都由逗号分隔的值组成,您可以使用将单个值作为数组来获取。使用(或者为每个循环使用一个)可以清除这些值,例如,使用删除空白和删除括号。
要将数组转换回行,可以使用。可以使用字符串或更好的字符串收集行
以下是一个例子:
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();
StringBuilder sb=新建StringBuilder();
试一试{
Files.lines(Path.of(“test.txt”)).forEach(x->{
字符串[]split=x.split(“,”);
拆分=流(拆分).map(y->{
字符串已清理=y.strip().replaceAll(“>$|^