好得很程序员自学网

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

java_IO向文件中写入和读取内容代码实例

使用java中outstream()向文件中写入内容

?

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

package stream;

 

import java.io.file;

import java.io.filenotfoundexception;

import java.io.fileoutputstream;

import java.io.ioexception;

import java.io.outputstream;

 

 

public class outstreamdemo01 {

     public static void main(string[] args) {

         //定义文件路径,没有该文件会自动创建,如果路径有文件夹,一定要有,不会自动创建文件夹

         string filename = "e:" +file.separator+ "a" +file.separator+ "b.txt" ;

         file file = new file(filename);

         string str = "这些都将写入文件中" ;

         byte [] b = str.getbytes();  //将字符串转换成字节数

         outputstream out = null ;

         try {

             out = new fileoutputstream(file);   //实例化outpurstream

         } catch (filenotfoundexception e){

             e.printstacktrace();

         }

        

         //写入

         try {

             out.write(b);       //写入

             out.close();        //关闭

         } catch (ioexception e) {

             // todo auto-generated catch block

             e.printstacktrace();

         }

     }

}

使用inputstream()读取文件中的内容:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

package stream;

import java.io.*;;

public class inputstreamdemo01 {

     public static void main(string[] args) {

         file file = new file( "e:" +file.separator+ "a" +file.separator+ "b.txt" );

         byte [] b = new byte [( int )file.length()]; //定义byte字节的长度

         inputstream in = null ;

         int len = 0 ;

         try {       //处理异常

             in = new fileinputstream(file);     //实例化fileinputstream类

         } catch (filenotfoundexception e) {

             // todo auto-generated catch block

             e.printstacktrace();        //输出异常

         }

         try {

             len = in.read(b);       //读取指定文件的内容

             in.close();

         } catch (ioexception e) {

             // todo auto-generated catch block

             e.printstacktrace();

         }

         system.out.println( new string(b, 0 ,len)); //将字节数组转化成字符串输出指定文件从0开始到len字节结束

     }

}

以上所述是小编给大家介绍的java_io向文件中写入和读取内容详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

原文链接:https://blog.csdn.net/weixin_44411569/article/details/88701088

查看更多关于java_IO向文件中写入和读取内容代码实例的详细内容...

  阅读:12次