企业的网站建设怎么记科目重庆高端seo
Java中的流,可以从不同的角度进行分类。
按照数据流的方向不同可以分为:输入流和输出流。
按照处理数据单位不同可以分为:字节流和字符流。
可以用下面的图来描述下:
字节流中的输入流的一些应用:代码如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;public class FileInputStreamTest {public static void main(String[] args) throws Exception{//找到目标文件File file=new File("d:/shareming/22.txt");// 建立数据输出通道FileInputStream is=new FileInputStream("d:/shareming/22.txt");//读取文件的方式byte[] buffer=new byte[5];int length=0;while(-1!=(length=is.read(buffer))){String result=new String(buffer,0,length);System.out.println(result);}is.close();}}
字节流中的输出流的一些应用(打印乘法表)+异常处理:代码如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class FileOutputStreamTest {public static void main(String[] args) {// 找到目标文件File file = new File("d:/shareming/22.txt");// 建立数据输出通道FileOutputStream fileOutPutStream;try {fileOutPutStream = new FileOutputStream(file);for (int i = 1; i <= 9; i++) {for (int j = 1; j <= i; j++) {// System.out.print(i+"*"+j+"="+i*j+"\t");String data = i + "*" + j + "=" + i * j + "\t";fileOutPutStream.write(data.getBytes());}String data = "\r\n";//把乘法表写进文件中fileOutPutStream.write(data.getBytes());}System.out.println("打印成功");fileOutPutStream.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blockSystem.out.println("找不到目录");e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
字节流中的输出流的一些应用(复制)+异常处理:代码如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class FileOutputStreamTest2 {public static void main(String[] args) {//找到目标文件File infile=new File("d:/shareming/22.txt");File destFile=new File("d:/shareming/23.txt");//建立数据输出通道FileInputStream fileInPutStream = null;FileOutputStream flleOutPutStream = null;try {fileInPutStream = new FileInputStream(infile);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {flleOutPutStream = new FileOutputStream(destFile);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}//从infile里面把数据读出来,然后把写进destfile里面byte[]buf=new byte[1024];int length=0;try {while((length=fileInPutStream.read(buf))!=-1){flleOutPutStream.write(buf,0,length);}} catch (IOException e) {// TODO Auto-generated catch blockSystem.out.println("读取失败");e.printStackTrace();}System.out.println("copy success");try {flleOutPutStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {fileInPutStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
常见的异常
ClassCastException 类转换异常 比如Person类转成String类
正确写法为:
NullPointerException 空指针异常
IndexOutOfBoundsException 下标越界异常