用java实现在txt文本中写数据和读数据的方法
更新时间:2018年07月24日 10:56:26 作者:征途無境
今天小编就为大家分享一篇用java实现在txt文本中写数据和读数据的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
向文本中写数据,一般这些数据我们用来做自动化测试。通过我们制定的一些生成数据的规则,能够快速写数据到文本中。
下面是写数据到txt文本(当然我们可以根据自己的需要写到doc、docx、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 = null; FileWriter fw = null; file = new File("F:\\JMeterRes\\Data\\test123.txt"); try { if (!file.exists()) { file.createNewFile(); } fw = new FileWriter(file); for(int i = 1;i <=3000;i++){ fw.write("abcdefgabcdefg"+i+",");//向文件中写内容 fw.write("sssssssssssssss"+i+",\r\n"); fw.flush(); } System.out.println("写数据成功!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(fw != null){ try { fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
上边写数据成功后会提示“写数据成功!”,然后我们读数据,代码如下:
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class ReadFiledata { public static String txt2String(File file){ StringBuilder result = new StringBuilder(); try{ BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件 String s = null; while((s = br.readLine())!=null){//使用readLine方法,一次读一行 result.append(System.lineSeparator()+s); } br.close(); }catch(Exception e){ e.printStackTrace(); } return result.toString(); } public static void main(String[] args){ File file = new File("F:/JMeterRes/Data/test123.txt"); System.out.println(txt2String(file)); } }
读出来的数据,如下图所示:
以上这篇用java实现在txt文本中写数据和读数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Spring中@RabbitHandler和@RabbitListener的区别详析
@RabbitHandler是用于处理消息的方法注解,它与@RabbitListener注解一起使用,这篇文章主要给大家介绍了关于Spring中@RabbitHandler和@RabbitListener区别的相关资料,需要的朋友可以参考下2024-02-02在Spring Boot2中使用CompletableFuture的方法教程
这篇文章主要给大家介绍了关于在Spring Boot2中使用CompletableFuture的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起看看吧2019-01-01调用Mybatis plus中的saveBatch方法报找不到表的问题
在用Mybatis plus开发的项目中,用自带的API批量保存的方法saveBatch操作时,发现报没有找到表的错误,本文就来详细的介绍一下解决方法,感兴趣的可以了解一下2024-03-03
最新评论