服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - 用java实现在txt文本中写数据和读数据的方法

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

2021-05-20 13:56征途無境 Java教程

今天小编就为大家分享一篇用java实现在txt文本中写数据和读数据的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

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

下面是写数据到txt文本(当然我们可以根据自己的需要写到doc、docx、xlx、xlsx等格式的文件中)的代码:

java" id="highlighter_843934">
?
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文本中写数据和读数据的方法

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

原文链接:https://blog.csdn.net/MenofGod/article/details/79071531

延伸 · 阅读

精彩推荐