好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java中FileOutputStream流的write方法

本文为大家分享了fileoutputstream流的 write 方法,供大家参考,具体内容如下

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

/*------------------------

fileoutputstream:

../输出流,字节流

../write(byte[] b)方法: 将b.length个字节从指定字节数组写入此文件输出流中

../write(byte[] b, int off, int len)方法:将指定字节数组中从偏移量off开始的len个字节写入此文件输出流

-------------------------*/

package pack02;

 

import java.io.*;

 

public class demo {

 

  public static void main(string[] args) {

  

   testmethod1(); //从程序中向一个文件写入数据

   testmethod2(); //复制一个文件的内容到另一个文件

  }

 

  //从程序中向一个文件写入数据

  public static void testmethod1() {

  

   file file1 = new file( "d:/test/myfile1.txt" );

   fileoutputstream fos = null ;

  

   try {

   

    fos = new fileoutputstream(file1); //将fileoutputstream流对象连接到file1代表的文件

   

    fos.write( new string( "this is myfile1.txt" ).getbytes() );

    //使用方法write(byte[] b),即向文件写入一个byte数组的内容

    //这里创建一个字符串对象,并调用方法getbytes(),将其转换成一个字符数组作为write(byte[] b)的形参

    //当文件myfile1.txt不存在时,该方法会自动创建一个这个文件;当文件已经存在时,该方法会创建一个新的同名文件进行覆盖并写入数组内容

   

   } catch (ioexception e) {

   

    e.printstacktrace();

   

   } finally {

   

    if ( fos != null )

     try {

      fos.close(); //关闭流

     } catch (ioexception e) {

      e.printstacktrace();

     }

   }

  }

 

  //从一个文件读取数据,然后写入到另一个文件中;相当于内容的复制

  public static void testmethod2() {

  

   file filein = new file( "d:/test/myfile2.txt" ); //定义输入文件

   file fileout = new file( "d:/test/myfile3.txt" ); //定义输出文件

  

   fileinputstream fis = null ;

   fileoutputstream fos = null ;

  

   try {

   

    fis = new fileinputstream(filein); //输入流连接到输入文件

    fos = new fileoutputstream(fileout); //输出流连接到输出文件

   

    byte [] arr = new byte [ 10 ]; //该数组用来存入从输入文件中读取到的数据

    int len; //变量len用来存储每次读取数据后的返回值

   

    while ( ( len=fis.read(arr) ) != - 1 ) {

     fos.write(arr, 0 , len);

    } //while循环:每次从输入文件读取数据后,都写入到输出文件中

   

   } catch (ioexception e) {

    e.printstacktrace();

   }

  

   //关闭流

   try {

    fis.close();

    fos.close();

   } catch (ioexception e) {

    e.printstacktrace();

   }

  }

 

}

注: 希望与各位读者相互交流,共同学习进步。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://www.cnblogs.com/EarthPioneer/p/9360029.html

查看更多关于Java中FileOutputStream流的write方法的详细内容...

  阅读:44次