用java實現(xiàn)在txt文本中寫數(shù)據(jù)和讀數(shù)據(jù)的方法
向文本中寫數(shù)據(jù),一般這些數(shù)據(jù)我們用來做自動化測試。通過我們制定的一些生成數(shù)據(jù)的規(guī)則,能夠快速寫數(shù)據(jù)到文本中。
下面是寫數(shù)據(jù)到txt文本(當(dāng)然我們可以根據(jù)自己的需要寫到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+",");//向文件中寫內(nèi)容
fw.write("sssssssssssssss"+i+",\r\n");
fw.flush();
}
System.out.println("寫數(shù)據(jù)成功!");
} 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();
}
}
}
}
}
上邊寫數(shù)據(jù)成功后會提示“寫數(shù)據(jù)成功!”,然后我們讀數(shù)據(jù),代碼如下:
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));//構(gòu)造一個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));
}
}
讀出來的數(shù)據(jù),如下圖所示:

以上這篇用java實現(xiàn)在txt文本中寫數(shù)據(jù)和讀數(shù)據(jù)的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用WebUploader實現(xiàn)上傳文件功能(一)
這篇文章主要為大家詳細(xì)介紹了使用WebUploader實現(xiàn)上傳文件功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01
java算法之靜態(tài)內(nèi)部類實現(xiàn)雪花算法
這篇文章主要介紹了java算法之靜態(tài)內(nèi)部類實現(xiàn)雪花算法,對算法感興趣的同學(xué),一定要看一下2021-05-05

