{ "title": "Java 文件读写与对象转换:将文本数据解析为 Student 对象", "description": "本示例演示如何使用 Java 代码读取文件内容,将文本数据解析为 Student 对象,并打印输出。代码涵盖文件读写、字符串分割、数据类型转换等操作,适合初学者学习参考。", "keywords": "Java, 文件读写, 对象转换, Student, 文件解析, 字符串分割, 数据类型转换", "content": "public static void main(String[] args) throws FileNotFoundException {\nfileout();\n}\npublic static void fileout() throws FileNotFoundException {\nFile file=new File("D:/file2/result2.txt");\nFileOutputStream out=new FileOutputStream(file);\nString str="小明-18-90;小红-17-95;老刚-29-60";\ntry {\nout.write(str.getBytes());\n} catch (IOException e) {\ne.printStackTrace();\n}\ntry {\nout.close();\n} catch (IOException e) {\ne.printStackTrace();\n}\n}\n}\n\n//读取方法\npublic static void main(String[] args) throws FileNotFoundException {\nfilein();\n}\npublic static void filein() throws FileNotFoundException {\nFile file = new File("D:/file2/result2.txt");\nFileInputStream in = new FileInputStream(file);\ntry { \nint size = in.available();\nbyte[] buffer = new byte[size];\nin.read(buffer);\nString str = new String(buffer, "UTF-8");\nSystem.out.println(str);\n} catch (IOException e) {\ne.printStackTrace();\n} finally {\ntry {\nin.close();\n} catch (IOException e) {\ne.printStackTrace();\n}\n}\n}\n}\n将文件内容转为Student对象内容:您可以使用以下代码将文件内容转换为Student对象:\n\njava\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\n\npublic class Main {\npublic static void main(String[] args) throws FileNotFoundException {\nfilein();\n}\n\npublic static void filein() throws FileNotFoundException {\nFile file = new File("D:/file2/result2.txt");\nFileInputStream in = new FileInputStream(file);\ntry {\nint size = in.available();\nbyte[] buffer = new byte[size];\nin.read(buffer);\nString str = new String(buffer, "UTF-8");\nString[] studentData = str.split(";");\nfor (String data : studentData) {\nString[] studentInfo = data.split("-");\nString name = studentInfo[0];\nint age = Integer.parseInt(studentInfo[1]);\nint score = Integer.parseInt(studentInfo[2]);\nStudent student = new Student(name, age, score);\nSystem.out.println(student);\n}\n} catch (IOException e) {\ne.printStackTrace();\n} finally {\ntry {\nin.close();\n} catch (IOException e) {\ne.printStackTrace();\n}\n}\n}\n}\n\nclass Student {\nprivate String name;\nprivate int age;\nprivate int score;\n\npublic Student(String name, int age, int score) {\nthis.name = name;\nthis.age = age;\nthis.score = score;\n}\n\n@Override\npublic String toString() {\nreturn "Student{" +\n"name='" + name + '\'' +\n", age=" + age +\n", score=" + score +\n'}';\n}\n}\n\n\n这段代码首先通过读取文件内容,将其转换为字符串。然后,使用分隔符将字符串拆分为每个学生的数据。再使用分隔符将每个学生的数据拆分为姓名、年龄和分数。最后,根据这些数据创建Student对象,并打印输出。

Java 文件读写与对象转换:将文本数据解析为 Student 对象

原文地址: https://www.cveoy.top/t/topic/p7rE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录