Java 如何将文本从textfile转换为对象的字段
好的,我得到一个文本文件,标记它,然后尝试将它写入另一个文件 我有一个名为course的类,它有4个参数:名称、级别、代码、年份 我已将文本文件的每一行划分为不同的一行 @编辑:应该在前面提到这一点,但我有3000门课程存储在一个文本文件中Java 如何将文本从textfile转换为对象的字段,java,variables,text-files,bufferedreader,tokenize,Java,Variables,Text Files,Bufferedreader,Tokenize,好的,我得到一个文本文件,标记它,然后尝试将它写入另一个文件 我有一个名为course的类,它有4个参数:名称、级别、代码、年份 我已将文本文件的每一行划分为不同的一行 @编辑:应该在前面提到这一点,但我有3000门课程存储在一个文本文件中 public void readFromFile() throws IOException { int index = 0; int j = -1; int spaceCount = 0; courseNumber++;
public void readFromFile() throws IOException
{
int index = 0;
int j = -1;
int spaceCount = 0;
courseNumber++;
setCourseFields();
BufferedReader inputFile = new BufferedReader(new FileReader(INPUT_FILE));
PrintWriter outputFile = new PrintWriter(new FileWriter(OUTPUT_FILE));
String lineOfText = inputFile.readLine();
while (lineOfText != null)
{
outputFile.println(lineOfText);
lineOfText = inputFile.readLine();
for (char c : lineOfText.toCharArray())
{
if (c == ' ')
{
spaceCount++;
}
}
if(spaceCount == 1)
{
delimiter = DELIMITER_SPACE;
}
else if(spaceCount == 2)
{
delimiter = DELIMITER_TAB;
}
System.out.println("Course" + courseNumber + "\n");
// for each token in the string
while ((j = lineOfText.indexOf(delimiter, (index = ++j))) != -1)
{
System.out.println(courseField[k] + ": " + lineOfText.substring(index, j));
counter++;
k++;
}
// extract the last token
if (index > 0)
{
System.out.println("Year: " + lineOfText.substring(index));
++courseNumber;
}
if(k == 3)
{
k = k - k;
index = 0;
}
delayDisplay();
} // while(lineOfText != null)
inputFile.close();
outputFile.close();
}
然后我会得到这样的东西
Course1
Name: Computer Engineering Technology
Level: IB
Code: TEJ4M
Year: 2017
Course2
Name: Communications Technology
Level: Special Education
Code: TGJ2O
Year: 2002
每门课程都是唯一的,我需要帮助,以便将上面的每个字符串分配给一个变量
每门课程有4个实例字段+一个唯一的序列号课程号
这4个字段是:
String name;
char level;
String code;
int academicYear;
我想用这四行中的每一行制作课程
这是我的课程
public class Course extends Object implements Serializable
{
// class constants
public static final String DEFAULT_CODE = "AAA10";
public static final char DEFAULT_LEVEL = 'X';
public static final String DEFAULT_NAME = "unassigned";
public static final int DEFAULT_YEAR = 1900;
private static final char ACADEMIC_LEVEL = '1';
private static final char ENGLISH_LANGUAGE_LEARNERS_LEVEL = '9';
private static final int ERROR_CODE = -1;
private static final char IB_LEVEL = '7';
private static final int MAXIMUM_YEAR = 2014;
private static final int MINIMUM_YEAR = 1900;
private static final char SPECIAL_EDUCATION_LEVEL = '8';
// instance variables
private int academicYear;
private String code;
private static int counter = 0;
private char level;
private String name;
private int serialNumber;
/**
* Constructs a course with default characteristics.
*/
public Course()
{
this.academicYear = DEFAULT_YEAR;
this.code = DEFAULT_CODE;
this.level = DEFAULT_LEVEL;
this.name = DEFAULT_NAME;
serialNumber = ++counter;
} // end of constructor Course()
/**
* Constructs a course with the specified characteristics.
*
* @param name - the Ministry-assigned name of this course;
* ex: Introduction to Computer Science
* @param code - the Ministry-assigned code of this course; ex: ICS3U
* @param level - one of the enumerated levels ex: '7', '1', '9', '8'
* @param academicYear - a 4-digit year of the Gregorian calendar
* set between a minimum and maximum year
*/
public Course(String name, String code, char level, int academicYear)
{
if(name == null)
{
this.name = DEFAULT_NAME;
}
else
{
this.name = name;
} // end of if(name == null)
if(code == null)
{
this.code = DEFAULT_CODE;
}
else
{
this.code = code;
} // end of if(code == null)
if (level == IB_LEVEL || level == ACADEMIC_LEVEL
|| level == ENGLISH_LANGUAGE_LEARNERS_LEVEL
|| level == SPECIAL_EDUCATION_LEVEL)
{
this.level = level;
}
else
{
this.level = DEFAULT_LEVEL;
} // end of if (level == IB_LEVEL || level == ACADEMIC_LEVEL || level ==
ENGLISH_LANGUAGE_LEARNERS_LEVEL || level == SPECIAL_EDUCATION_LEVEL )
if (academicYear >= MINIMUM_YEAR && academicYear <= MAXIMUM_YEAR)
{
this.academicYear = academicYear;
}
else
{
this.academicYear = DEFAULT_YEAR;
} // end of (academicYear >= MINIMUM_YEAR && academicYear <= MAXIMUM_YEAR)
serialNumber = ++counter;
} // end of constructor Course(String name, String code, char level, int academicYear)
/* Comparison methods*/
/**
* Indicates whether another object has a state identical to this object’s state.
*
* @param otherCourse - the object whose state is compared to this object’s
*
* @return true if the other object has an identical state; otherwise false
*/
public boolean equals(Object otherCourse)
{
if(otherCourse == null) return false;
if (this.getClass() != otherCourse.getClass()) return false;
if (this == otherCourse) return true;
// Typecasting Object otherCourse into a Course to compare objects' states
Course course1 = (Course) otherCourse;
if(serialNumber != course1.getSerialNumber()) return false;
if(academicYear != course1.getYear()) return false;
if(level != course1.getLevel()) return false;
if(code != course1.getCode()) return false;
if(name != course1.getName()) return false;
// needed to satisfy the compiler
return true;
} // end of method boolean equals(Object course)
/**
* Indicates whether another object has a state identical to this object’s state,
* ignoring each object's unique serial number.
*
* @param otherCourse - the object whose state is compared to this object’s
*
* @return true if the other object has an identical state; otherwise false
*/
public boolean equalsIgnoreSerial(Object otherObject)
{
if(otherObject == null) return false;
if (this.getClass() != otherObject.getClass()) return false;
boolean courseEquals;
Course anotherCourse = (Course) otherObject;
// Ignore unique serial number of each course
if(this.serialNumber == anotherCourse.getSerialNumber()) return false;
if(this.academicYear != anotherCourse.getYear()) return false;
else courseEquals = true;
if(this.level != anotherCourse.getLevel()) return false;
else courseEquals = true;
if(this.code != anotherCourse.getCode()) return false;
else courseEquals = true;
if(this.name != anotherCourse.getName()) return false;
else courseEquals = true;
return courseEquals;
} // end of method boolean equalsIgnoreSerial(Object course
/**
* Compares this Course to another.
*
* @return a negative value, if this course should come before the other course;
* 0, if this course and the other course have equal states;
* a positive value if this course should come after the other course
*/
public int compareTo(Course otherCourse)
{
int before = -1;
int after = 1;
int equals = 0;
int resultCode = code.compareTo(otherCourse.getCode());
int resultName = name.compareTo(otherCourse.getName());
if(otherCourse == null) return -1;
if(this.equals(otherCourse)) return equals;
if(serialNumber < otherCourse.getSerialNumber()) return before;
if(serialNumber > otherCourse.getSerialNumber()) return after;
if(academicYear < otherCourse.getYear()) return before;
if(academicYear > otherCourse.getYear()) return after;
if(!(sortLevel(level) == -1 || sortLevel(otherCourse.getLevel()) == -1))
{
if(sortLevel(level) < sortLevel(otherCourse.getLevel())) return before;
if(sortLevel(level) > sortLevel(otherCourse.getLevel())) return after;
} // end of if(!(sortLevel(level) == -1 || sortLevel(otherCourse.getLevel()) ==
-1))
if(code.compareTo(otherCourse.getCode()) != 0) return resultCode;
if(name.compareTo(otherCourse.getName()) != 0) return resultName;
// neccessary to satisfy the compiler
return 5;
} // end of public int compareTo(Course otherCourse)
/* utility methods*/
public static int sortLevel(char level)
{
/*************************************
final char[] LEVEL = {'7', '1', '9', '8'};
for (int index = 0; index < LEVEL.length; index++)
{
if(LEVEL[index] == level) return index;
if(LEVEL[index] != level) return ERROR_IO_EXCEPTION;
} // end of for (int index = 0; index < LEVEL.length; index++)
// error code for not found, should not be reached
return -1;
****************************************/ //code taken from in class discussion
final char[] LEVEL = {'7', '1', '9', '8'};
for (int index = 0; index < LEVEL.length; index++)
{
if(LEVEL[index] == level) return index;
if(LEVEL[index] != level) return -1;
} // end of for (int index = 0; index < LEVEL.length; index++)
// error code for not found, should not be reached
return ERROR_CODE;
} // end of public static int sortLevel(char level)
/* accessors*/
/**
* Returns the code of this course.
*
* @returns Returns the code of this course
*/
public String getCode()
{
return code;
} // end of method getCode()
/**
* Returns the level of this course.
*
* @return the level of this course
*/
public char getLevel()
{
return level;
} // end of method getLevel()
/**
* Returns the name of this course.
*
* @return the name of this course.
*/
public String getName()
{
return name;
} // end of method getName()
/**
* Returns the unique serial number of this course.
*
* @return the unique serial number of this course.
*/
public int getSerialNumber()
{
return serialNumber;
} // end of method getSerialNumber()
/**
* Returns the academic year of this course.
*
* @return the 4-digit academic year of this course
*/
public int getYear()
{
return academicYear;
} // end of method getYear()
/* mutators */
/**
* Sets the code of this course.
*
* @param newCode - the new code of this course.
*/
public void setCode(String newCode)
{
if (newCode == null) return;
this.code = newCode;
} // end of method setCode(String newCode)
/**
* Sets the level of this course.
*
* @param newLevel - one of the enumerated levels
*/
public void setLevel(char newLevel)
{
if(newLevel == IB_LEVEL || newLevel == ACADEMIC_LEVEL || newLevel ==
ENGLISH_LANGUAGE_LEARNERS_LEVEL || newLevel == SPECIAL_EDUCATION_LEVEL)
{
level = newLevel;
}
else
{
level = DEFAULT_LEVEL;
} // end of if(newLevel == IB_LEVEL || newLevel == ACADEMIC_LEVEL || newLevel ==
ENGLISH_LANGUAGE_LEARNERS_LEVEL || newLevel == SPECIAL_EDUCATION_LEVEL)
} // end of method setLevel(char newLevel)
/**
* Sets the name of this course.
*
* @param newName - the new name of this course
*/
public void setName(String newName)
{
if (newName == null) return;
this.name = newName;
} // end of method setName(String newName)
/**
* Sets the academic year of this course.
*
* @param newYear - the new 4-digit academic year of this course
*/
public void setYear(int newYear)
{
if (newYear >= MINIMUM_YEAR && newYear <= MAXIMUM_YEAR)
{
this.academicYear = newYear;
}
else
{
academicYear = DEFAULT_YEAR;
} // end of if (newYear >= MINIMUM_YEAR && newYear <= MAXIMUM_YEAR)
} // end of method setYear(int newYear)
/**
* Returns a string representation of this course.
*
* @override toString in class Object
*
* @return a string representation of this course.
*/
public String toString()
{
return
this.getClass().getName()
+"["
+ "Serial Number: " + serialNumber
+ ", academic year: " + academicYear
+ ", level: " + level
+ ", code: " + code
+ ", name: " + name
+"]";
} // end of String toString()
我想我明白你的问题了。您正在分析字段,但没有保存它们。您可以做的一件事是保存字段。将它们存储在HashMap中,其中键是字段的名称。然后使用HashMap检索字段并调用构造函数:
// for each token in the string
HashMap<String,String> hm = new HashMap<String,String>(); //NEW
while ((j = lineOfText.indexOf(delimiter, (index = ++j))) != -1)
{
hm.put(courseField[k], lineOfText.substring(index, j)); //NEW
System.out.println(courseField[k] + ": " + lineOfText.substring(index, j));
counter++;
k++;
}
// extract the last token
if (index > 0)
{
System.out.println("Year: " + lineOfText.substring(index));
hm.put("Year", lineOfText.substring(index)); //NEW
++courseNumber;
}
//translate level string to a character
char lvl;
String sLevel = hm.get("Level");
if (sLevel.equals("IB"))
lvl = '7';
else if (sLevel.equals("Special Education"))
lvl = '8';
else if (sLevel.equals("Academic"))
lvl = '8';
else if (sLevel.equals("English Language Learners"))
lvl = '1';
else
lvl = ' '; /* unknown level */
//create the Course object
Course c = new Course(hm.get("Name"), hm.get("Code"), lvl , Integer.parseInt(hm.get("Year")) );
这些不是参数。这些是类的属性、实例变量或属性。另外,不要大写int。您的课程类是否有构造函数?@EdwinTorres是的,它确实可以扫描您发布的课程类?这将有助于查看构造函数、变量等。您还需要提供唯一的序列号。这将从何而来?@EdwinTorres我分享了我的课程类顺便说一句,equals方法不应该像现在这样比较字符串,如果!name.equals course1.getName返回false;我在一个文本文件中有3000个这样的课程,我如何解决这个问题,比如创建object,好吧,这是一个不同的问题。您应该在获取课程数据的同一循环中创建对象。一旦你有了所有需要的数据,就调用你的构造函数。这会创建3000个不同的课程吗?检索字段并调用构造函数是什么意思当你调用hm.getName时,它会检索存储在键名下的值。这就是HashMap的工作原理。在解析字段时,HashMap临时存储字段。它会创造3000门课程吗?那要看情况。您的WHILE循环是否显示所有3000个课程?
// for each token in the string
HashMap<String,String> hm = new HashMap<String,String>(); //NEW
while ((j = lineOfText.indexOf(delimiter, (index = ++j))) != -1)
{
hm.put(courseField[k], lineOfText.substring(index, j)); //NEW
System.out.println(courseField[k] + ": " + lineOfText.substring(index, j));
counter++;
k++;
}
// extract the last token
if (index > 0)
{
System.out.println("Year: " + lineOfText.substring(index));
hm.put("Year", lineOfText.substring(index)); //NEW
++courseNumber;
}
//translate level string to a character
char lvl;
String sLevel = hm.get("Level");
if (sLevel.equals("IB"))
lvl = '7';
else if (sLevel.equals("Special Education"))
lvl = '8';
else if (sLevel.equals("Academic"))
lvl = '8';
else if (sLevel.equals("English Language Learners"))
lvl = '1';
else
lvl = ' '; /* unknown level */
//create the Course object
Course c = new Course(hm.get("Name"), hm.get("Code"), lvl , Integer.parseInt(hm.get("Year")) );