首先是按行读取字符串
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 按行读取文件按行写入文件并以空格分割字符串的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/hdg745979749/article/details/78049013
查看更多关于Java 按行读取文件按行写入文件并以空格分割字符串的方法的详细内容...