Java 按行读取文件按行写入文件并以空格分割字符串的方法

2025-05-29 0 56

首先是按行读取字符串

?

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

35

36
import java.io.bufferedreader;

import java.io.file;

import java.io.filereader;

public class txtchange {

public static void main(string[] args){

file file=new file("e:\\\\olddata.txt");

bufferedreader reader=null;

string temp=null;

int line=1;

try{

reader=new bufferedreader(new filereader(file));

while((temp=reader.readline())!=null){

// system.out.println("第"+line+"行:"+temp);

string string=analyzestr.getanalyze().getnewstring(temp);//调用分割方法

system.out.println(string);

analyzestr.getanalyze().saverecordinfile(string);//调用按行存储字符串

line++;

}

}

catch(exception e){

e.printstacktrace();

}

finally{

if(reader!=null){

try{

reader.close();

}

catch(exception e){

e.printstacktrace();

}

}

}

}

}

按照空格分割字符串并重新组合成新的字符串

空是”\\s”,是转义字符,需要使用”\\s”,“+”代表一个或者多个空格

?

1

2

3

4

5

6

7

8

9

10
public string getnewstring(string filename){

string str1="";

string str2="";

string str3="";

string []arraystr=filename.split("\\\\s+");

str1="\\n\\t\\t"+arraystr[0];

str2="\\t"+arraystr[1];

str3="\\t"+arraystr[2];

return str1+str2+str3;

}

然后按行保存字符串方法,path是保存的路径,例如“d://test.txt”

?

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
//追加记录

public void saverecordinfile(string str) {

file record = new file(path);//记录结果文件

try {

if (!record.exists()) {

file dir = new file(record.getparent());

dir.mkdirs();

record.createnewfile();

}

filewriter writer = null;

try {

// 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件

writer = new filewriter(record, true);

writer.write(str);

} catch (ioexception e) {

e.printstacktrace();

} finally {

try {

if (writer != null) {

writer.close();

}

} catch (ioexception e) {

e.printstacktrace();

}

}

} catch (exception e) {

system.out.println("记录保存失败");

}

}

以上这篇java 按行读取文件按行写入文件并以空格分割字符串的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/hdg745979749/article/details/78049013

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java 按行读取文件按行写入文件并以空格分割字符串的方法 https://www.kuaiidc.com/111551.html

相关文章

发表评论
暂无评论