本文主要介绍使用FileWriter类和BufferedWriter类对文件进行字符串的写入操作,以及使用Scanner类实现对文件的读取操作,最终实现自定义类的属性储存和读取,希望能对同学们有帮助,如有不足还请多多指出
·使用编译器:
· 测试学生类定义(这里为了便于储存与使用,使用的全是字符串格式):
public class Student
{
String id ;
String name ;
String age ;
public Student()
{}
public Student( String id , String name , String age ) //有参构造方便后续
{
this.id = id ;
this.name = name ;
this.age = age ;
}
}
·主函数代码如下:
import java.util.Scanner ;
import java.io.* ;
public class Main {
public static void main(String[] args)
{
File file = new File( "D:\\系统默认\\桌面\\Data.txt" ) ;//打开文件
FileWriter fileWriter = null ;
BufferedWriter bufferedWriter = null ; //FileWriter和BufferedWriter的初始化需要监听,此处只定义不初始化
Scanner sc = null ; //同上
Student[] stu = new Student[3] ;
stu[0] = new Student( "001" , "喜羊羊" , "6" ) ;
stu[1] = new Student( "002" , "懒羊羊" , "6" ) ;
stu[2] = new Student( "007" , "灰太狼" , "20" ) ;
try
{
fileWriter = new FileWriter( file ) ;
bufferedWriter = new BufferedWriter( fileWriter ) ;
for( int i = 0 ; i < stu.length ; i ++ ) //将学生类全部写入文件,bufferWirter可直接写入字符串,支持中文
{
bufferedWriter.write( stu[i].id ) ;
bufferedWriter.write( " " ) ;
bufferedWriter.write( stu[i].name ) ;
bufferedWriter.write( " " ) ;
bufferedWriter.write( stu[i].age );
bufferedWriter.write( " " ) ;
bufferedWriter.newLine() ; //每输入一个学生都另起一行
}
}
catch( Exception e )
{
System.out.println( "Error." ) ;
}
finally
{
try
{
bufferedWriter.close(); //随手关闭文件,此处注意关闭顺序不能错误
fileWriter.close();
}
catch( IOException ioe )
{
}
}
}
}
·运行结果,正常运行后相应文件的内容:
·则文件储存代码部分正常,这部分需要注意文件的关闭顺序错误的话不会报错,但也无法储存任何信息。
·Student类没有改变,主函数代码如下:
import java.util.Scanner ;
import java.io.* ;
public class Main {
public static void main(String[] args)
{
File file = new File( "D:\\系统默认\\桌面\\Data.txt" ) ; //打开文件
Scanner sc = null ;
Student[] stu = new Student[3] ;
try
{
sc = new Scanner( file ) ;
for( int i = 0 ; i < stu.length ; i ++ )
{
stu[i] = new Student( sc.next() , sc.next() , sc.next() ) ; //注意此处即使不使用有参构造来读取信息,也要进行一次无参构造的初始化
}
System.out.println( "ID\t名字\t年龄\t" ) ;
for( int i = 0 ; i < stu.length ; i ++ )
{
System.out.println( stu[i].id + "\t" + stu[i].name + "\t" + stu[i].age );
}
}
catch( Exception e )
{
System.out.println( "Error." ) ;
}
finally
{
try
{
sc.close();
}
catch ( Exception e )
{
}
}
}
}
·如过读取正常,则运行结果如下:
"D:\IntelliJ IDEA Community Edition 2023.1.2\SDK\bin\java.exe" "-javaagent:D:\IntelliJ IDEA Community Edition 2023.1.2\lib\idea_rt.jar=59525:D:\IntelliJ IDEA Community Edition 2023.1.2\bin" -Dfile.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8 -classpath "D:\IntelliJ IDEA Community Edition 2023.1.2\Programme\Experiment_1\out\production\Experiment_1" Main
ID 名字 年龄
001 喜羊羊 6
002 懒羊羊 6
007 灰太狼 20
Process finished with exit code 0
由此便实现了我们今天要做的所有功能。
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务