如何在Java中逐行读取文本文件并排除某些以特定字符串开头的行
我想读取文本文件和输入数据,以便从输入参数创建Patient类对象。文本文件包含不同的行和类别,前几行包含患者类别的数据,后几行包含药物类别的数据,第三个类别包含医师类别的医师数据。如下 “myFile.txt”是我的文件名,包含以下数据 所以我想读取这个文件并输入数据,这样我就可以为Patient对象、drug对象和Medical对象创建相应类的对象。我尝试了以下方法,但我无法分割类别。我的程序代码读取所有文件并输入患者对象。因此,任何人的帮助都是感激的 注意:我已经在其他类文件中创建了类Patient、Drug和Medical,创建类没有问题。我只想从这个文本文件主类中读取数据并构建类对象。因此,我的问题只是如何基于类参数逐行读取文本文件,并从中提取数据作为类对象的输入 这是我的密码如何在Java中逐行读取文本文件并排除某些以特定字符串开头的行,java,input,line,filereader,Java,Input,Line,Filereader,我想读取文本文件和输入数据,以便从输入参数创建Patient类对象。文本文件包含不同的行和类别,前几行包含患者类别的数据,后几行包含药物类别的数据,第三个类别包含医师类别的医师数据。如下 “myFile.txt”是我的文件名,包含以下数据 所以我想读取这个文件并输入数据,这样我就可以为Patient对象、drug对象和Medical对象创建相应类的对象。我尝试了以下方法,但我无法分割类别。我的程序代码读取所有文件并输入患者对象。因此,任何人的帮助都是感激的 注意:我已经在其他类文件中创建了类P
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
public class Lsystem{
static ArrayList<Patient> pList;
static ArrayList<Drug> dList;
static ArrayList<Physician> plist;
public static void main(String[] args) throws FileNotFoundException{
pList = new ArrayList<Patient>();
dList = new ArrayList<Drug>();
plist = new ArrayList<Physician>() ;
File dataFile = new File("myFile.txt");
Scanner inputData = null;
try {
inputData = new Scanner(dataFile);
}
catch(Exception e) {
System.out.println(e);
System.exit(1);
}
// skip first line
String[] line = inputData.nextLine().split(" ");
//read next lines
while( inputData.hasNextLine()) {
if(!(inputData.hasNext("# drugs "))){
line = inputData.nextLine().split(",");
String name = line[0];
String securityNum = line[1];
Patient newPatient = new Patient(name,securityNum);
pList.add(newPatient);
}
}
for(Patient pas:pList){
System.out.println(pas);
}
else if ((inputData.hasNext("# drugs")))
while( inputData.hasNextLine() && (!(inputData.hasNext("# Physician ")))) {
line = inputData.nextLine().split(",");
String name = line[0];
String type = line[1];
double price = Double.parseDouble(line[2]);
double kg = Double.parseDouble(line[3]);
int conc = Integer.valueOf(line[4]);
Drug newDrug = new Drug(name,type,price,kg,conc);
dList.add(newDrug);
}
for(Drug drg:dList){
System.out.println(drg);
}
// an so on for Physician data as well
// .......
}
}
import java.util.Scanner;
导入java.util.ArrayList;
导入java.io.File;
导入java.io.FileNotFoundException;
公共类系统{
静态阵列列表;
静态数组列表;
静态阵列列表;
公共静态void main(字符串[]args)引发FileNotFoundException{
pList=新的ArrayList();
dList=newarraylist();
plist=新的ArrayList();
文件数据文件=新文件(“myFile.txt”);
扫描仪输入数据=空;
试一试{
inputData=新扫描仪(数据文件);
}
捕获(例外e){
系统输出打印ln(e);
系统出口(1);
}
//跳过第一行
String[]line=inputData.nextLine().split(“”);
//读下一行
while(inputData.hasNextLine()){
if(!(inputData.hasNext(#药品”)){
line=inputData.nextLine().split(“,”);
字符串名称=行[0];
字符串securityNum=行[1];
患者newPatient=新患者(姓名,securityNum);
pList.add(新患者);
}
}
用于(患者pas:pList){
系统输出打印项次(pas);
}
else if((inputData.hasNext(#药品”))
while(inputData.hasNextLine()&(!(inputData.hasNext(#内科医生))){
line=inputData.nextLine().split(“,”);
字符串名称=行[0];
字符串类型=行[1];
double price=double.parseDouble(第[2]行);
double kg=double.parseDouble(第[3]行);
int conc=整数.valueOf(第[4]行);
新药=新药(名称、类型、价格、千克、浓度);
添加(新药);
}
for(药品图纸:dList){
系统输出打印项次(drg);
}
//医生数据也是如此
// .......
}
}
希望这是您需要的(它很脏,但…):
我假设您的文本文件与下面的示例完全相同:
(文件->text.txt)
这是主要的(您必须更改e text.txt文件路径):
这使用
文件
和扫描仪
来处理问题中显示的输入文件。它假设文件严格遵循问题的示例。例如,必须有三个部分,每个部分中至少有一条记录。它还假设没有空行,甚至在文件末尾也没有
从这个意义上讲,此解决方案是脆弱的,并且缺少必要的错误检查和验证代码。否则,这就是问题的解决办法
有关其他注释,请参见代码
根据您的评论,重点可能是查看控制如何调用scanner.nextLine()
的逻辑
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.ArrayList;
public class ProcessDataFile {
// Our three lists for our three classes of object:
final List<Patient> patients = new ArrayList();
final List<Drug> drugs = new ArrayList();
final List<Physician> physicians = new ArrayList();
// The file scanner:
Scanner scanner;
// The currently processed line:
String line;
public void populateLists() throws FileNotFoundException {
File file = new File("C:/tmp/medical_data.txt");
scanner = new Scanner(file);
// process the file, one line at a time
while (scanner.hasNextLine()) {
line = scanner.nextLine();
processLine();
}
printResults();
}
// process each line in the file
private void processLine() {
if (line.startsWith("# Patient")) {
line = scanner.nextLine();
processPatients();
}
if (line.startsWith("# drug")) { // note the "d" in drug - not "D"!
line = scanner.nextLine();
processDrugs();
}
if (line.startsWith("# Physician")) {
line = scanner.nextLine();
processPhysicians();
}
}
private void processPatients() {
while (!line.startsWith("#")) {
String[] fields = line.split(",");
// TODO - add check to make sure 2 values are in the split string.
Patient patient = new Patient(
fields[0].trim(),
fields[1].trim());
patients.add(patient);
line = scanner.nextLine();
}
}
private void processDrugs() {
while (!line.startsWith("#")) {
String[] fields = line.split(",");
// TODO - add check to make sure 5 values are in the split string,
// and are of the expected data type:
Drug drug = new Drug(
fields[0].trim(),
fields[1].trim(),
Double.parseDouble(fields[2].trim()),
Double.parseDouble(fields[3].trim()),
Integer.parseInt(fields[4].trim()));
drugs.add(drug);
line = scanner.nextLine();
}
}
private void processPhysicians() {
while (!line.startsWith("#")) {
String[] fields = line.split(",");
// TODO - add check to make sure 2 values are in the split string,
// and are of the expected data type:
Physician physician = new Physician(
fields[0].trim(),
Long.parseLong(fields[1].trim()));
physicians.add(physician);
if (scanner.hasNextLine()) {
// this may be the end of the file already... this assumes
// that the physicians section is the final section.
line = scanner.nextLine();
} else {
return; // to avoid never exiting this method
}
}
}
private void printResults() {
patients.forEach((patient) -> {
System.out.println(patient.name + " : " + patient.securityNum);
});
// and the same for the other 2 beans...
}
}
如果添加了缺少的代码,它将打印出另外2个bean。看看Javadocs中的String类。让自己熟悉这一点,应该会给你所有你需要的。谢谢你的回复和代码,我很感激。我的问题是读取文件,我已经在单独的文件中创建了类。我想要的是根据class参数从文件中读取数据,并在主类中将其用作构建类对象的输入。有没有更简单的办法。虽然它有效,但你的方式有点复杂。我只想使用File&scanner类读取文本文件。没那么复杂。最后一个方法private void printResults()不起作用,其余的都可以,谢谢。错误是System.out.println(patient.name+“:”+patient.securityNum)找不到变量名和securityNum。您可以检查代码中是否有任何内容,或者是否有方法使用for循环为(patient-patient:patients){System.out.println(patient)打印输出@Sirway-我创建了自己的
Patient
类,它有自己的字段名,但没有getter或setter(因为我的代码只是为您演示的)。如果您使用患者
类中的字段名,或者更可能使用您可能创建的get
方法,那么您应该不会有问题。这对您来说应该是一个小小的更改。好的,我在我的类中实现了get方法,我做到了这一点,javac编译非常完美,但java没有输出任何东西。我的意思是没有输出它不会打印任何内容。我建议使用调试器,这样可以让您很快找到问题。如果您不确定从哪里开始,那么就开始。Netbeans和Eclipse是两个不错的选择,但也有其他选择。
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class MainTest {
public static void main(String[] args) throws Exception {
//set the path of your text file
File file = new File(MainTest.class.getClassLoader().getResource("text.txt").getFile());
Scanner myReader = new Scanner(file);
StringBuilder sb = new StringBuilder();
while (myReader.hasNextLine()) {
String tmp = myReader.nextLine();
sb.append(tmp + "\n");
}
myReader.close();
String[] type = sb.toString().split("#");
String patients = type[1];
String drugs = type[2];
String doctors = type[3];
patients = patients.replace("Patient (name, securityNum)\n","");
drugs = drugs.replace("drugs (name, type,pric,kg,concent)\n","");
doctors = doctors.replace("Physician (name, Idnum)\n","");
System.out.println("°°°°°°°°°°°°°°°°°°°°°°°°°°°");
populatePatientBean(patients).forEach( patient -> {
System.out.println("\nname " + patient.getName());
System.out.println("num " + patient.getSecurityNum());
});
populateDrugsBean(drugs).forEach( drugs_ -> {
System.out.println("\nname " + drugs_.getName());
System.out.println("type " + drugs_.getType());
System.out.println("concent " + drugs_.getConcent());
System.out.println("kg " + drugs_.getKg());
});
populatePhysicianBean(doctors).forEach( doctor -> {
System.out.println("\nname " + doctor.getName());
System.out.println("id " + doctor.getIdNum());
});
System.out.println("°°°°°°°°°°°°°°°°°°°°°°°°°°°");
}
public static List<Patient> populatePatientBean(String linePatient){
List<String> patientsTot = Arrays.asList(linePatient.split("\n"));
List<Patient> patientListReturn = new ArrayList<>();
patientsTot.forEach( line -> {
String[] arrayString = line.split(",");
Patient patient = new Patient(arrayString[0].trim(),arrayString[1].trim());
patientListReturn.add(patient);
});
return patientListReturn;
}
public static List<Drugs> populateDrugsBean(String lineDrugs){
List<String> drugsTot = Arrays.asList(lineDrugs.split("\n"));
List<Drugs> drugsListReturn = new ArrayList<>();
drugsTot.forEach( line -> {
String[] arrayString = line.split(",");
Drugs drugs = new Drugs(arrayString[0].trim(),arrayString[1].trim(),Float.valueOf(arrayString[2].trim()),Float.valueOf(arrayString[3].trim()),Float.valueOf(arrayString[4].trim()));
drugsListReturn.add(drugs);
});
return drugsListReturn;
}
public static List<Physician> populatePhysicianBean(String linePhysician){
List<String> physicianTot = Arrays.asList(linePhysician.split("\n"));
List<Physician> physicianListReturn = new ArrayList<>();
physicianTot.forEach( line -> {
String[] arrayString = line.split(",");
Physician physician = new Physician(arrayString[0].trim(),Long.valueOf(arrayString[1].trim()));
physicianListReturn.add(physician);
});
return physicianListReturn;
}}
public class Patient {
private String name;
private String securityNum;
public Patient(String name, String securityNum) {
this.name = name;
this.securityNum = securityNum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecurityNum() {
return securityNum;
}
public void setSecurityNum(String securityNum) {
this.securityNum = securityNum;
}
}
public class Drugs {
private String name;
private String type;
private float kg;
private float concent;
private float pric;
public Drugs(String name, String type, float kg, float concent, float pric) {
this.name = name;
this.type = type;
this.kg = kg;
this.concent = concent;
this.pric = pric;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public float getKg() {
return kg;
}
public void setKg(float kg) {
this.kg = kg;
}
public float getConcent() {
return concent;
}
public void setConcent(float concent) {
this.concent = concent;
}
public float getPric() {
return pric;
}
public void setPric(float pric) {
this.pric = pric;
}
}
public class Physician {
private String name;
private long idNum;
public Physician(String name, long idNum) {
this.name = name;
this.idNum = idNum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getIdNum() {
return idNum;
}
public void setIdNum(long idNum) {
this.idNum = idNum;
}
}
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.ArrayList;
public class ProcessDataFile {
// Our three lists for our three classes of object:
final List<Patient> patients = new ArrayList();
final List<Drug> drugs = new ArrayList();
final List<Physician> physicians = new ArrayList();
// The file scanner:
Scanner scanner;
// The currently processed line:
String line;
public void populateLists() throws FileNotFoundException {
File file = new File("C:/tmp/medical_data.txt");
scanner = new Scanner(file);
// process the file, one line at a time
while (scanner.hasNextLine()) {
line = scanner.nextLine();
processLine();
}
printResults();
}
// process each line in the file
private void processLine() {
if (line.startsWith("# Patient")) {
line = scanner.nextLine();
processPatients();
}
if (line.startsWith("# drug")) { // note the "d" in drug - not "D"!
line = scanner.nextLine();
processDrugs();
}
if (line.startsWith("# Physician")) {
line = scanner.nextLine();
processPhysicians();
}
}
private void processPatients() {
while (!line.startsWith("#")) {
String[] fields = line.split(",");
// TODO - add check to make sure 2 values are in the split string.
Patient patient = new Patient(
fields[0].trim(),
fields[1].trim());
patients.add(patient);
line = scanner.nextLine();
}
}
private void processDrugs() {
while (!line.startsWith("#")) {
String[] fields = line.split(",");
// TODO - add check to make sure 5 values are in the split string,
// and are of the expected data type:
Drug drug = new Drug(
fields[0].trim(),
fields[1].trim(),
Double.parseDouble(fields[2].trim()),
Double.parseDouble(fields[3].trim()),
Integer.parseInt(fields[4].trim()));
drugs.add(drug);
line = scanner.nextLine();
}
}
private void processPhysicians() {
while (!line.startsWith("#")) {
String[] fields = line.split(",");
// TODO - add check to make sure 2 values are in the split string,
// and are of the expected data type:
Physician physician = new Physician(
fields[0].trim(),
Long.parseLong(fields[1].trim()));
physicians.add(physician);
if (scanner.hasNextLine()) {
// this may be the end of the file already... this assumes
// that the physicians section is the final section.
line = scanner.nextLine();
} else {
return; // to avoid never exiting this method
}
}
}
private void printResults() {
patients.forEach((patient) -> {
System.out.println(patient.name + " : " + patient.securityNum);
});
// and the same for the other 2 beans...
}
}
Patient1 : 1234
Patient2 : 456