Java中如何通过txt文件存储和取出数据?

Python041

Java中如何通过txt文件存储和取出数据?,第1张

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}

首先创建一个新的txt文件,然后new File(“txt文件路径”),

封装一个输入输出流,将要写入的数据写入到txt中,刷新流,关闭流。

代码如下:

public static void main(String[] args) throws IOException{

String str = "这个项目什么时候上线"

File file//创建文件夹

FileOutputStream stream = null//new文件流

try {

file = new File("C:/Users/qisf/Desktop/Aa.txt")

stream = new FileOutputStream (file)//将文件夹放在文件流中

if (!file.exists()) {

file.createNewFile()

}

byte[] contentInBytes = str.getBytes()//转化成字节形

stream.write(contentInBytes)//写入

stream.flush()//写完之后刷新

stream.close()//关闭流

} catch (FileNotFoundException e) {

e.printStackTrace()

}

}

首先创建一个新的txt文件,然后new File(“txt文件路径”),

封装一个输入输出流,将要写入的数据写入到txt中,刷新流,关闭流。

代码如下:

public static void main(String[] args) throws IOException{

String str = "这个项目什么时候上线"

File file//创建文件夹

FileOutputStream stream = null//new文件流

try {

file = new File("C:/Users/qisf/Desktop/Aa.txt")

stream = new FileOutputStream (file)//将文件夹放在文件流中

if (!file.exists()) {

file.createNewFile()

}

byte[] contentInBytes = str.getBytes()//转化成字节形

stream.write(contentInBytes)//写入

stream.flush()//写完之后刷新

stream.close()//关闭流

} catch (FileNotFoundException e) {

e.printStackTrace()

}

}