字节流与字符流
字符流 Reader Writer
字节流 InputStream OutputStream
public static void main(String[] args){
FileWriter fw = null;
try{
fw = new FileWriter("demo.txt",true);
fw.write("abc");
fw.write("\r\n");
}
catch(Exception e){
e.printStack();
}
finally{
if(fw!=null){
try{
fw.close();
}
catch(IOException e){
e.printStack();
}
}
}
}
public static void main(String[] args){
FileReader fr = FileReader("demo.txt");
char[] buf = new char[1024];
int len = 0;
while(len=fr.read(buf)!=-1){
System.out.println(new String(buf,0,len));
}
fr.close();
}
while((len = fr.read(buf)) != -1){
fw.write(buf, 0, len);
流的操作:
//读
File file = new File("demo.txt");
if(file.exist()){
try{
FileInputStream fis = new FileInputStream(file);
BufferReader buf = new BufferReader(fis); //将字节流转为字符流
String text = buf.readLine();
//获得一行数据
}catch(Exception e){
e.printStackTrace();
}
}
//写
File file = new File("demo.txt");
FileOutputStream fos = null;
try{
fos = = new FileOutputStream(file);
fos.write("abc".getBytes());
fos.close();
}catch(Exception e){
e.printStackTrace();
}
import java.io.*;
class CopyPic
{
public static void main(String[] args)
{
FileOutputStream fos = null;
FileInputStream fis = null;
try
{
fos = new FileOutputStream("c:\\2.bmp");
fis = new FileInputStream("c:\\1.bmp");
byte[] buf = new byte[1024];
int len = 0;
while((len=fis.read(buf))!=-1)
{
fos.write(buf,0,len);
fw.flush();
}
}
catch (IOException e)
{
throw new RuntimeException("复制文件失败");
}
finally
{
try
{
if(fis!=null)
fis.close();
}
catch (IOException e)
{
throw new RuntimeException("读取关闭失败");
}
try
{
if(fos!=null)
fos.close();
}
catch (IOException e)
{
throw new RuntimeException("写入关闭失败");
}
}
}
}
字符输入流的缓冲区对象BufferedReader String readLine()
* 如果能用readLine()方法读取,省事多了
* 可以这个方法是字符流对象
*
* 控制台输入System.in字节流
*
* java的io体系中,可以做到,将字节流转成字符流处理数组
* 转换流: java.io.InputStreamReader
* 这个对象,可以将字节流转成字符流来操作,字节通向字符的桥梁
*/
import java.io.*;
public class TranseDemo1 {
public static void main(String[] args)throws IOException {
InputStream in = System.in;
OutputStream out = System.out;
//InputStreamReader(InputStream in)字节输入流
InputStreamReader isr = new InputStreamReader(in);
//字节输入流 in 就被转换成了字符流对象,字符流可以使用缓冲区对象
BufferedReader bfr = new BufferedReader(isr);
//控制台始终都是字节流,你向将数据写到字节流中,用人家换行(字符缓冲区的)
//将字符流,转成字节流 OutputStreamWriter
String line = null;
while((line = bfr.readLine())!=null){
if("over".equals(line))
break;
//out.write((line.toUpperCase()+"\r\n").getBytes());
}
}
}
IO流
最新推荐文章于 2024-11-04 22:09:25 发布