用java实现在txt文本中写数据和读数据的方法

2025-05-29 0 102

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

下面是写数据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文本中写数据和读数据的方法

以上这篇用java实现在txt文本中写数据和读数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/MenofGod/article/details/79071531

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 用java实现在txt文本中写数据和读数据的方法 https://www.kuaiidc.com/111263.html

相关文章

发表评论
暂无评论