您的位置:首页 > 其它

读取一个文本文档,例如有1~10行,要求按10~1行的顺序输出.并保存予原文件

2009-02-16 10:11 501 查看
Java代码

package test49;

//package com.color.io;

/*
* Main.java
*
* Created on 2000年9月29日, 下午5:17
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

/**
*
* @author admin
*/
public class Main {

/** Creates a new instance of Main */
public Main() {
}

/**
* @param args
* the command line arguments
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
// 按文件大小来产生构建buffer
char[] buffer = new char[(int) new File("D://新建 文本文档.txt").length()];
Reader reader = null;
try {
reader = new FileReader("D://新建 文本文档.txt");

int offset;
while ((offset = reader.read(buffer)) > 0)
System.out.print(new String(buffer, 0, offset));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
}
}
// 将整个文件读入,然后构造成一个String
String s = new String(buffer);
// 将这个String按换行符拆分成String数组
String[] reverse = s.split("/r/n");
// 构造文件,原来那个文件
File file = new File("D://新建 文本文档.txt");
Writer writer = new FileWriter(file);
for (int i = reverse.length - 1; i >= 0; i--) {
// 反转写入
writer.write(reverse[i] + "/r/n");
}
writer.close();
}

}

或者

Java代码

package test49;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;

public class TxtReverse {

/**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
FileReader fr = new FileReader(new File("d://a.txt"));
BufferedReader br = new BufferedReader(fr);
ArrayList<String> al = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
al.add(line);
}

for (int i = al.size() - 1; i >= 0; i--) {
System.out.println(al.get(i));
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐