首先是按行读取字符串
?
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
相关文章
猜你喜欢
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 99
-
2025-05-29 64
-
2025-05-25 32
-
2025-06-04 84
-
2025-05-25 17
热门评论