用java實現(xiàn)在txt文本中寫數(shù)據(jù)和讀數(shù)據(jù)的方法
向文本中寫數(shù)據(jù),一般這些數(shù)據(jù)我們用來做自動化測試。通過我們制定的一些生成數(shù)據(jù)的規(guī)則,能夠快速寫數(shù)據(jù)到文本中。
下面是寫數(shù)據(jù)到txt文本(當然我們可以根據(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));//構造一個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)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
詳解JAVA中ListIterator和Iterator的辨析
這篇文章主要為大家詳細介紹了JAVAListIterator和Iterator的辨析,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02詳解Java使用雙異步后如何保證數(shù)據(jù)一致性
這篇文章主要為大家詳細介紹了Java使用雙異步后如何保證數(shù)據(jù)一致性,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以了解下2024-01-01mybatis-generator-gui根據(jù)需求改動示例
這篇文章主要為大家介紹了mybatis-generator-gui根據(jù)需求改動示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09SpringBoot定時監(jiān)聽RocketMQ的NameServer問題及解決方案
這篇文章主要介紹了SpringBoot定時監(jiān)聽RocketMQ的NameServer問題及解決方案,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-12-12