javaSE基础编程——字节流

来源:互联网 发布:mysql update 自关联 编辑:程序博客网 时间:2024/05/17 23:28



在某处新建一个文件,随便写入一些内容,编写程序检查看该文件是否存在;

若存在,则读出文件中的内容。

再编写程序实现文件的写操作

package com.cissst.software.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.junit.Test;
/*
 * 字节流
 * 2015-8-7

* 读字节流是将已经写好的文件中的内容读出来,要提前把文件创建好并在里面写好内容
 * 写字节流是要在程序中指定好的文件中写入内容,不需要提前创建文件
 */
public class ReadFile {
// 读文件
 @Test
 public void testFile1() throws Exception{
  //创建File对象
  File file = new File("D:\\外包文件练习\\test.txt");
  if(!file.exists()){
   System.out.println("文件不存在");
   return;
  }
  //创建FileInputStream对象
  FileInputStream f = new FileInputStream(file);
  //读取文件内容 
  int c = 0;
  while(true){
   c = f.read();
   if(c==-1){
    break;
   }
   System.out.print((char)c);
  }
  //关闭输入流
  f.close();
 }
 
 /*
  * 字节流读文件
  * 2015-8-7
  */
 @Test
 public void testFile2() throws Exception{
  //创建File对象
  File file = new File("D:\\外包文件练习\\test.txt");
  if(!file.exists()){
   System.out.println("文件不存在");
   return;
  }
  //创建FileInputStream对象
  FileInputStream f = new FileInputStream(file);
  //读取文件内容 
  int c = 0;
  while((c = f.read())!=-1){
   System.out.print((char)c);
  }
  //关闭输入流
  f.close();
 }
 
 /*
  * 字节流写文件
  * 2015-8-7
  */
 @Test
 public void testFile3() throws Exception{
  //创建FileInputStream对象
  FileOutputStream out = null;
  try {
   //创建FileInputStream对象
   out = new FileOutputStream("D:\\外包文件练习\\temp.txt");
   //写文件内容
   String st = "hello!";
   //将文件转换为字符串数组
   byte[] b = st.getBytes();
   //写入文件
   out.write(b);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
  //关闭输入流
   try {
    out.close();
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}

0 0
原创粉丝点击