一、将数据读出来显示到console内:
代码如下:
package InputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class OutputStreamWriterDemo {
public static void main(String[] args) throws IOException {
//创建输入流对象
BufferedReader br = new BufferedReader(new FileReader(“copy.txt”));
//method1(br);
//创建输出流对象
Writer w=new OutputStreamWriter(System.out); //转换成字符流
BufferedWriter bw = new BufferedWriter(w);
String line ;
while((line = br.readLine())!=null) {
bw.write(line);
bw.newLine();
}
br.close();
bw.close();
}
private static void method1(BufferedReader br) throws IOException {
OutputStream os = System.out;
String line;
while((line = br.readLine())!=null) {
os.write(line.getBytes());
os.write("
".getBytes());
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
}
二、将数据从console输入存到制定的文本中
代码如下:
package InputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class InputStreamReaderDemo {
public static void main(String[] args) throws IOException {
//method1();
InputStream is = System.in; //将键盘输入的数据存入到is里面
Reader r= new InputStreamReader(is); //用r来读取is里面的数据,将字节转换成字符类型的
FileWriter fw = new FileWriter("c.txt"); //用fw来将r读出来的数据写入到c.txt里面
char [] ch = new char[1024];
int len;
while((len = r.read(ch))!=-1) {
fw.write(ch,0,len);
fw.flush();
}
fw.close();
r.close();
}
private static void method1() throws IOException {
InputStream is = System.in;
FileWriter fw = new FileWriter("b.txt");
int len;
byte [] byt = new byte [1024];
while((len = is.read(byt))!=-1) {
fw.write(new String(byt,0,len));
fw.flush();
}
is.close();
fw.close();
}