java IO 文件读入,写入,重定向 - 天堂有路慢慢走,俯首甘为博之牛 - ITeye技术网站
- package star20110526;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintStream;
- import java.io.PrintWriter;
- public class Redirecting {
- public static void main(String[] args) throws IOException {
- redirect();
- // readFile();
- // write("B05\\star20110526\\Redirecting.txt", read());
- }
- private static void redirect() throws IOException{
- //将输出定位到PrintStrem,将 System.out重新定义ouputStream
- PrintStream printStream = System.out;
- //定义输入流
- BufferedInputStream bufferedInputStream = new BufferedInputStream(
- new FileInputStream("B05\\star20110526\\Redirecting.java"));
- //定义输出流
- PrintStream printStream2 = new PrintStream(
- new BufferedOutputStream(new FileOutputStream("B05\\star20110526\\Redirect.out")));
- //本来System.in是接受控制台参数的,现在将System.in重新定义到bufferedInputStream
- System.setIn(bufferedInputStream);
- System.setErr(printStream2);
- System.setOut(printStream2);
- //InputStreamReader 为适配器,转换inputStream到Reader,你懂的
- BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
- String string;
- while((string = bufferedReader.readLine()) != null){
- System.out.println(string);
- }
- printStream.close();
- printStream2.close();
- bufferedReader.close();
- System.setOut(printStream);
- }
- /**
- * 读取文件,然后直接在控制台打印出来
- * @throws IOException
- */
- private static void readFile() throws IOException{
- File file = new File("B05\\star20110526\\Redirecting.java");
- FileReader fileReader = new FileReader(file);
- BufferedReader bufferedReader = new BufferedReader(fileReader);
- int i = 1;
- String string;
- while((string = bufferedReader.readLine()) != null){
- System.out.println(i++ +":"+string);
- }
- bufferedReader.close();
- }
- /**
- * 读取文件,返回文件内容,提供文件写入操作
- * @return
- * @throws IOException
- */
- private static String read() throws IOException{
- File file = new File("B05\\star20110526\\Redirecting.java");
- BufferedReader bufferedReader = new BufferedReader(
- new FileReader(file));
- StringBuilder stringBuilder = new StringBuilder();
- String string;
- while((string = bufferedReader.readLine()) != null){
- stringBuilder.append(string+"\n");
- }
- return stringBuilder.toString();
- }
- /**
- * 新建一个文件,然后往文件里面写文件咯
- * @param file
- * @param text
- * @throws FileNotFoundException
- */
- private static void write(String file,String text) throws FileNotFoundException{
- File file2 = new File(file);
- PrintWriter printWriter = new PrintWriter(file2);
- printWriter.write(text);
- //必须关闭流,要不然出不来结果的,(╰_╯)#(╰_╯)#(╰_╯)#
- printWriter.close();
- }
- }