怎么用java实现在txt文本中写数据和读数据

  介绍

小编给大家分享一下怎么用java实现在txt文本中写数据和读数据,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!

向文本中写数据,一般这些数据我们用来做自动化测试。通过我们制定的一些生成数据的规则,能够快速写数据到文本中。

<强>下面是写数据到txt文本(当然我们可以根据自己的需要写到医生,多克斯,xlx, xlsx等格式的文件中)的代码:

import  java.io.File;   import  java.io.FileWriter;   import  java.io.IOException;   public  class  Test  {   public  static  void  main (String [], args), {   File 才能;File =,空;   FileWriter 才能;fw =,空;   file 才能=,new 文件(“F: \ \ JMeterRes \ \数据\ \ test123.txt");   try {才能   ,,if  (! file.exists ()), {   ,,,file.createNewFile ();   ,,}   ,,fw =, new  FileWriter(文件);   ,,(int 小姐:=,1;小姐:& lt;=3000;我+ +){   ,,fw.write (“abcdefgabcdefg" +我+“,“);//向文件中写内容   ,,fw.write (“sssssssssssssss" +我+“\ r \ n");   ,,fw.flush ();   ,,}   ,,System.out.println(“写数据成功!“);   ,,},catch  (IOException  e), {   ,,//,TODO  Auto-generated  catch 块   ,,e.printStackTrace ();   最后}{才能   ,,如果(fw  !=, null) {   ,,,try  {   ,,,,fw.close ();   ,,,},catch  (IOException  e), {   ,,,,//,TODO  Auto-generated  catch 块   ,,,,e.printStackTrace ();   ,,,}   ,,}   ,,}   ,}   }

<>强上边写数据成功后会提示”写数据成功!”,然后我们读数据,代码如下:

import  java.io.BufferedReader;   import  java.io.File;   import  java.io.FileReader;   ,   public  class  ReadFiledata  {   ,public  static  String  txt2String (File 文件){   StringBuilder 才能;result =, new  StringBuilder ();   尝试才能{   ,,BufferedReader  br =, new  BufferedReader (new  FileReader(文件));//构造一个BufferedReader类来读取文件   ,,String  s =,空;   ,,,((=s  br.readLine ()) !=null){//使用readLine方法,一次读一行   ,,,result.append (System.lineSeparator () + s);   ,,}   ,,br.close (),,   }才能赶上(Exception  e) {   ,,e.printStackTrace ();   ,,}   return 才能result.toString ();   ,}   ,   ,public  static  void  main (String [], args) {   File 才能;File =, new 文件(“F:/JMeterRes/数据/test123.txt");   System.out.println才能(txt2String(文件);   ,}   }

<>强读出来的数据,如下图所示:

怎么用java实现在txt文本中写数据和读数据

以上是“怎么用java实现在txt文本中写数据和读数据”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!

怎么用java实现在txt文本中写数据和读数据