向文本中写数据,一般这些数据我们用来做自动化测试。通过我们制定的一些生成数据的规则,能够快速写数据到文本中。
下面是写数据到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文本中写数据和读数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。
原文链接:https://blog.csdn.net/MenofGod/article/details/79071531
相关文章
猜你喜欢
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
将Sublime Text 2固定到Ubuntu启动器的方法
2025-05-25 90 -
2025-06-04 40
-
2025-06-05 54
-
2025-05-25 81
-
2025-05-25 24
热门评论