java 按行读取一个文件,存在字符串数组里,一个元素对应一行,再将这个数组按行输出到一个新的文件里
发布网友
发布时间:2022-05-01 05:23
我来回答
共2个回答
热心网友
时间:2023-10-08 01:32
java 按行读取一个文件,存在字符串数组里,一个元素对应一行,再将这个数组按行输出到一个新的文件里,代码如下:
package foo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
File readFile=new File("D://home/a.txt");
InputStream in=null;
InputStreamReader ir=null;
BufferedReader br=null;
OutputStream out=null;
OutputStreamWriter ow=null;
BufferedWriter bw=null;
try {
//用流读取文件
in=new BufferedInputStream(new FileInputStream(readFile));
//如果你文件已utf-8编码的就按这个编码来读取,不然又中文会读取到乱码
ir=new InputStreamReader(in,"utf-8");
br=new BufferedReader(ir);
String line="";
//定义集合一行一行存放
List<String> list=new ArrayList<String>();
//一行一行读取
while((line=br.readLine())!=null){
System.out.println(line);
list.add(line);
}
//将集合转换成数组
String[] arr=list.toArray(new String[list.size()]);
//写入新文件
File newFile=new File("D://home/b.txt");
if(!newFile.exists()){
newFile.createNewFile();
}
out=new BufferedOutputStream(new FileOutputStream(newFile));
//这里也可以给定编码写入新文件
ow=new OutputStreamWriter(out,"gb2312");
bw=new BufferedWriter(ow);
//遍历数组吧字符串写入新文件中
for(int x=0;x<arr.length;x++){
bw.write(arr[x]);
if(x!=arr.length-1){
//换行
bw.newLine();
}
}
//刷新该流的缓冲,这样才真正写入完整到新文件中
bw.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
//一定要关闭流,倒序关闭
try {
if(bw!=null){
bw.close();
}
if(ow!=null){
ow.close();
}
if(out!=null){
out.close();
}
if(br!=null){
br.close();
}
if(ir!=null){
ir.close();
}
if(in!=null){
in.close();
}
} catch (Exception e2) {
}
}
}
}
热心网友
时间:2023-10-08 01:32
import java.io.*;
import java.util.ArrayList;
public class ReadAndOut {
static String[] ary;
static final String READ_PATH="c:\\test.txt";
static final String OUT_PATH="c:\\test2.txt";
public static void main(String[] args) throws Exception {
//首先读取文件,
ArrayList<String> list = new ArrayList<String>();
File file = new File(READ_PATH);
BufferedReader br = new BufferedReader(new FileReader(file));
String temp;
while((temp=br.readLine())!=null){
list.add(temp);
}
br.close();
//然后存到数组中
ary = new String[list.size()];//从集合存到数组中
for (int i = 0; i < list.size(); i++) {
ary[i] = list.get(i);
}
//最后把数组的元素,输出出去
BufferedWriter bw = new BufferedWriter(new FileWriter(OUT_PATH));
for (int i = 0; i < ary.length; i++) {
bw.write(ary[i]);
bw.newLine();
}
bw.close();
}
}