加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 19:47:49 所属栏目:Java 来源:网络整理
导读:向文本中写数据,一般这些数据我们用来做自动化测试。通过我们制定的一些生成数据的规则,能够快速写数据到文本中。 下面是写数据到txt文本(当然我们可以根据自己的需要写到doc、docx、xlx、xlsx等格式的文件中)的代码: import java.io.File;import java.

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

下面是写数据到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:JMeterResDatatest123.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+",rn");
   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));
 }
}

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

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

您可能感兴趣的文章:

  • java 实现读取txt文本数据并以数组形式一行一行取值
  • java实现读取txt文件中的内容
  • java实现数据库的数据写入到txt的方法
  • JAVA实现读取txt文件内容的方法

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读