- <P>import java.io.*;
- class FileStream
- {
- public static void main(String[] args)
- {
- read_2();
- //read_1();
- //write();
- }
- public static void read_2()
- {
- FileInputStream fis = null;
- try
- {
- fis = new FileInputStream("FileStreamDemo.txt");
- int ch =0;
- while((ch = fis.read())!=-1)
- {
- System.out.println(ch);\<FONT color=red>\打印出一串数字,如果加char 强转是一串问号
- </FONT> }
- }
- catch (IOException e)
- {
- System.out.println(e.toString());
- }
- finally
- {
- if (fis!=null)
- {
- try
- {
- fis.close();
- }
- catch (IOException e)
- {
- System.out.println("close failed");
- }
- }
- }
- }
- public static void read_1()
- {
- FileInputStream fis = null;
- try
- {
- fis = new FileInputStream("FileStreamDemo.txt");//FileStreamDemo.txt 这个文件里边写的是中文
- int len =0;
- byte[] b = new byte[1024];
- while((len=fis.read(b))!=-1)
- {
- System.out.println(new String(b,0,len));\<FONT color=red>\可以打印出中文,这个为什么可以打印出中文??b里边装的不也是单个的字节吗? 既然是字节打印结果应该和上面那个方法的打印结果一样呀??为什么这个能打出中文,上面的却是数字??
- </FONT> }
- }
- catch (IOException e)
- {
- System.out.println(e.toString());
- }
- finally
- {
- if (fis!=null)
- {
- try
- {
- fis.close();
- }
- catch (IOException e)
- {
- System.out.println(e.toString());
- }
- }
- }
- }
- public static void write()
- {
- FileOutputStream fos = null;
- try
- {
- fos = new FileOutputStream("FileStreamDemo.txt");
- fos.write("谁在天堂".getBytes());
- }
- catch (IOException e)
- {
- System.out.println("catch"+"写入失败 ");
- }
- finally
- {
- if(fos!=null)
- try
- {
- fos.close();
- }
- catch (Exception e)
- {
- System.out.println(e.toString());
- }
- }
- }
- }</P>
复制代码 |
|