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文件的内容:
因此实现想要的效果。
我的实现方案是: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对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树