本文主要介绍使用FileWriter类和BufferedWriter类对文件进行字符串的写入操作,以及使用Scanner类实现对文件的读取操作,最终实现自定义类的属性储存和读取,希望能对同学们有帮助,如有不足还请多多指出
目录
·使用编译器:
1.测试定义学生类并储存如文件
· 测试学生类定义(这里为了便于储存与使用,使用的全是字符串格式):
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 )
{
}
}
}
}
·运行结果,正常运行后相应文件的内容:
·则文件储存代码部分正常,这部分需要注意文件的关闭顺序错误的话不会报错,但也无法储存任何信息。
2.使用Scanner类面向文件读取学生信息
·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
由此便实现了我们今天要做的所有功能。
3.总结
嗯...其实没什么好总结的,如果你不明白FileWriter类的操作方法可以去CSDN上看一看别的大大的文章,当然其实只要会用就行。try的作用就是字如其名就是监听报错的作用,欢迎大家一起交流讨论,有错误的地方欢迎指出。