发布网友 发布时间:2022-04-22 11:32
共1个回答
热心网友 时间:2023-09-05 08:14
Java中读取txt文件可以使用file类先创建一个对象,然后使用I/O操作,进行读取或者写入操作,示例如下:\x0d\x0aimportjava.io.BufferedReader;\x0d\x0aimportjava.io.File;\x0d\x0aimportjava.io.FileInputStream;\x0d\x0aimportjava.io.FileNotFoundException;\x0d\x0aimportjava.io.FileOutputStream;\x0d\x0aimportjava.io.IOException;\x0d\x0aimportjava.io.InputStreamReader;\x0d\x0aimportjava.io.PrintWriter;\x0d\x0a\x0d\x0apublicclassdemo2{\x0d\x0aprivatestaticStringpath="f:/demo1.txt";\x0d\x0aprivatestaticFilefile;\x0d\x0astatic{\x0d\x0afile=newFile(path);\x0d\x0aif(!file.exists()){\x0d\x0atry{\x0d\x0afile.createNewFile();\x0d\x0a}catch(IOExceptione){\x0d\x0ae.printStackTrace();\x0d\x0a}\x0d\x0a}\x0d\x0a}\x0d\x0a\x0d\x0apublicstaticvoidmain(String[]args)throwsIOException{\x0d\x0aStudentstu=newStudent(1,"张三",90);\x0d\x0awriteDataToFile(file,stu);\x0d\x0areadDataFromFile(file);\x0d\x0a}\x0d\x0a\x0d\x0aprivatestaticvoidreadDataFromFile(Filefile)throwsIOException{\x0d\x0aBufferedReaderreader=newBufferedReader(newInputStreamReader(newFileInputStream(file)));\x0d\x0aStringstr="";\x0d\x0awhile((str=reader.readLine())!=null){\x0d\x0aString[]stuInfo=str.split(",");\x0d\x0aSystem.out.println("学号:"+stuInfo[0]+"姓名:"+stuInfo[1]+"score:"+stuInfo[2]);\x0d\x0a}\x0d\x0a}\x0d\x0a\x0d\x0aprivatestaticvoidwriteDataToFile(Filefile,Studentstu)throwsFileNotFoundException{\x0d\x0aPrintWriterout=newPrintWriter(newFileOutputStream(file,true));\x0d\x0aout.println(stu.toString());\x0d\x0aout.close();\x0d\x0a}\x0d\x0a}