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

这篇博客介绍了如何使用Java进行文本数据的读写操作,特别是在自动化测试场景下。示例代码展示了如何创建并写入一个txt文件,以及如何读取文件内容。通过`FileWriter`写入数据,并用`BufferedReader`读取,实现对txt文件的高效操作。
摘要由CSDN通过智能技术生成

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

下面是写数据到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));

}

}

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

70bec9cc7691034a674a41a28fd18205.png

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值