向文本中写 数据 ,一般这些数据我们用来做自动化测试。通过我们制定的一些生成数据的规则,能够快速写数据到文本中。
下面是写数据到 txt 文本(当然我们可以根据自己的需要写到doc、docx、xlx、xlsx等格式的文件中)的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
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(); } } } } } |
上边写数据成功后会提示[写数据成功!],然后我们读数据,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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文本中写数据和读数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/MenofGod/article/details/79071531
查看更多关于用java实现在txt文本中写数据和读数据的方法的详细内容...