您的位置:首页 > 编程语言 > Java开发

java 中的写入后换行

2016-03-30 16:25 405 查看
在Java 中,对于.txt 文件的每一行读入可以找到对应的方法 readLine()  。然而对于写入.txt文件中要求逐行写入却没有对应的方法。但是在Java 开发中找到对应的策略使得逐行读入的内容可以实现逐行写入。

 我的实现方案是:String str=reader.readLine()+"\r\n";   再将写入文件中将会实现换行写入   。 
 实现的代码如下:

 package test;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.io.IOException;

/**

 * 对于文件进行读和写的操作

 * @author Administrator

 *

 */

public class Input_Output {

public static void main(String[] args) throws Exception {
// 路径
String path1="D://an//matlab test//a.text";
String path2="D://an//matlab test//b.text" ;
//创建两个文件
File file1=new File(path1);
File file2=new File(path2);
if(!file1.isFile()){
file1.createNewFile();
}
if(!file2.isFile()){
file2.createNewFile();
}
// 文件创建完成后  创建读写流
FileReader fr=new FileReader(file1);
@SuppressWarnings("resource")
BufferedReader reader=new BufferedReader(fr);
@SuppressWarnings("resource")
FileOutputStream out=new FileOutputStream(file2);
while(reader.read()!=-1){
 

String str=reader.readLine()+"\r\n";
// 写入文件b.txt中

//打印出来
   
   byte [] ss=str.getBytes();

   out.write(ss);
System.out.println(str);
}

} }

  对应文中的a.txt  内容:



写入b.txt文件的内容:



因此实现想要的效果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java