java如何从文本文档中提取信息,然后将其打印出来
我想问一下如何从txt文档中提取信息(我的txt文档包含
Baggins, Bilbo, < bilbobaggins@bagend.com >, Y
Baggins, Frodo, < frodobaggins@bagend.com >, N
我试过一些东西。我还想知道如何将每个部分存储在变量中,以便在字符串生成器/使用中编辑它们。修剪以去除空白
这就是我所尝试的:
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等
# 1 楼答案
有关如何在Java中读取文件,请参见此question。 因为每一行似乎都由逗号分隔的值组成,所以您可以使用split将各个值作为数组来获取。使用streams(或者为每个循环使用a)可以清除这些值,例如,使用strip删除空白,使用replaceAll删除括号。 要将数组转换回一行,可以使用join。可以使用
String
或更好的StringBuilder收集行以下是一个例子: