java读取文件流,java文件流读取文件

本文目录一览:

用java读取文件流,文件进程被java独占,怎样

可以通过BufferedReader流的形式进行流读取,之后通过readLine方法获取到读取的内容。BufferedReaderbre=null;try{Stringfile=”D:/test/test.txt”;bre=newBufferedReader(newFileReader(file));//此时获取到的bre就是整个文件的

java中文件的读取实现,以及用到哪些类

ava.io包中包括许多类提供许多有关文件的各个方面操作。

1 输入输出抽象基类InputStream/OutputStream ,实现文件内容操作的基本功能函数read()、 write()、close()、skip()等;一般都是创建出其派生类对象(完成指定的特殊功能)来实现文件读写。在文件读写的编程过程中主要应该注意异常处理的技术。

2 FileInputStream/FileOutputStream:

用于本地文件读写(二进制格式读写并且是顺序读写,读和写要分别创建出不同的文件流对象);

本地文件读写编程的基本过程为:

① 生成文件流对象(对文件读操作时应该为FileInputStream类,而文件写应该为FileOutputStream类);

② 调用FileInputStream或FileOutputStream类中的功能函数如read()、write(int b)等)读写文件内容;

③ 关闭文件(close())。

3 PipedInputStream/PipedOutputStream:

用于管道输入输出(将一个程序或一个线程的输出结果直接连接到另一个程序或一个线程的输入端口,实现两者数据直接传送。操作时需要连结);

4管道的连接:

方法之一是通过构造函数直接将某一个程序的输出作为另一个程序的输入,在定义对象时指明目标管道对象

PipedInputStream pInput=new PipedInputStream();

PipedOutputStream pOutput= new PipedOutputStream(pInput);

方法之二是利用双方类中的任一个成员函数 connect()相连接

PipedInputStream pInput=new PipedInputStream();

PipedOutputStream pOutput= new PipedOutputStream();

pinput.connect(pOutput);

5 管道的输入与输出:

输出管道对象调用write()成员函数输出数据(即向管道的输入端发送数据);而输入管道对象调用read()成员函数可以读起数据(即从输出管道中获得数据)。这主要是借助系统所提供的缓冲机制来实现的。

6随机文件读写:

RandomAccessFile类(它直接继承于Object类而非InputStream/OutputStream类),从而可以实现读写文件中任何位置中的数据(只需要改变文件的读写位置的指针)。

随机文件读写编程的基本过程为:

① 生成流对象并且指明读写类型;

② 移动读写位置;

③ 读写文件内容;

④ 关闭文件。

java中关于文件流的读写(Writer Reader)

你好 我刚刚做了个例子 方便你看

class_writer class 这个例子是从 一个文件中读取数据然后插入了数据库中 你可以只看读取与插入的过程 希望能帮到你.

public class writer {

public boolean writ(String str) {

boolean success=false;

str = str.replaceAll(” “, “”).replaceAll(“\””, “”);

String[] strs = str.split(“,”);

BaseJDBC base = new BaseJDBC();

String ML = “”;

Statement stmt;

Connection conn;

ML = “‘”+strs[0].replace(” “, “”).trim() + “‘,'”

+ strs[1].replace(” “, “”).trim() + “‘,'”

+ strs[2].replace(” “, “”).trim() + “‘,'”

+ strs[3].replace(” “, “”).trim() + “‘,'”

+ strs[4].replace(” “, “”).trim()+ “‘,'”

+ strs[5].replace(” “, “”).trim()+”‘,'”

+ strs[6].replace(” “, “”).trim()+”‘”;

String query = “INSERT INTO BANK_INFO VALUES(” + ML + “)”;

if (!strs[0].equals(“参与者行号”)) {

try {

conn=base.genConn();

stmt = conn.createStatement();

int num=stmt.executeUpdate(query);

if(num==1)success=true;

stmt.close();

conn.close();

System.out.println();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

System.out.println(e.getMessage());

}

}

return success;

}

//class readingclass

public class reading {

public static void readFileByLines(String fileName) {

File file = new File(fileName);

BufferedReader reader = null;

try {

reader = new BufferedReader(new FileReader(file));

String tempString = null;

int line = 1;

while ((tempString = reader.readLine()) != null) {

writer w=new writer();

try {

tempString.getBytes(“utf-8”);

} catch (UnsupportedEncodingException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

if(!w.writ(tempString)){

System.out.println(“第”+line+”行出现异常:”+tempString);

}else{

System.out.println(“第”+line+”行初始化成功!”);

}

line++;

}

reader.close();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (reader != null) {

try {

reader.close();

} catch (IOException e1) {

}

}

}

}

//1927

public static void main(String[] args) {

// TODO Auto-generated method stub

String fileName = “D:\\BankInfo_20110714094211.csv”;

readFileByLines(fileName);

}

java如何读取文件流是什么格式

直接用fileinputstream读文件到内存,然后用outputstream输出到客户端,因为是二进制流操作,源文件是什么格式,输出的就是什么格式。

java输入输出流是怎么读取的呢

读取文件吧。

public class ReadFromFile {

    /**

     * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。

     */

    public static void readFileByBytes(String fileName) {

        File file = new File(fileName);

        InputStream in = null;

        try {

            System.out.println(“以字节为单位读取文件内容,一次读一个字节:”);

            // 一次读一个字节

            in = new FileInputStream(file);

            int tempbyte;

            while ((tempbyte = in.read()) != -1) {

                System.out.write(tempbyte);

            }

            in.close();

        } catch (IOException e) {

            e.printStackTrace();

            return;

        }

        try {

            System.out.println(“以字节为单位读取文件内容,一次读多个字节:”);

            // 一次读多个字节

            byte[] tempbytes = new byte[100];

            int byteread = 0;

            in = new FileInputStream(fileName);

            ReadFromFile.showAvailableBytes(in);

            // 读入多个字节到字节数组中,byteread为一次读入的字节数

            while ((byteread = in.read(tempbytes)) != -1) {

                System.out.write(tempbytes, 0, byteread);

            }

        } catch (Exception e1) {

            e1.printStackTrace();

        } finally {

            if (in != null) {

                try {

                    in.close();

                } catch (IOException e1) {

                }

            }

        }

    }

    /**

     * 以字符为单位读取文件,常用于读文本,数字等类型的文件

     */

    public static void readFileByChars(String fileName) {

        File file = new File(fileName);

        Reader reader = null;

        try {

            System.out.println(“以字符为单位读取文件内容,一次读一个字节:”);

            // 一次读一个字符

            reader = new InputStreamReader(new FileInputStream(file));

            int tempchar;

            while ((tempchar = reader.read()) != -1) {

                // 对于windows下,\r\n这两个字符在一起时,表示一个换行。

                // 但如果这两个字符分开显示时,会换两次行。

                // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。

                if (((char) tempchar) != ‘\r’) {

                    System.out.print((char) tempchar);

                }

            }

            reader.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

        try {

            System.out.println(“以字符为单位读取文件内容,一次读多个字节:”);

            // 一次读多个字符

            char[] tempchars = new char[30];

            int charread = 0;

            reader = new InputStreamReader(new FileInputStream(fileName));

            // 读入多个字符到字符数组中,charread为一次读取字符数

            while ((charread = reader.read(tempchars)) != -1) {

                // 同样屏蔽掉\r不显示

                if ((charread == tempchars.length)

                         (tempchars[tempchars.length – 1] != ‘\r’)) {

                    System.out.print(tempchars);

                } else {

                    for (int i = 0; i  charread; i++) {

                        if (tempchars[i] == ‘\r’) {

                            continue;

                        } else {

                            System.out.print(tempchars[i]);

                        }

                    }

                }

            }

        } catch (Exception e1) {

            e1.printStackTrace();

        } finally {

            if (reader != null) {

                try {

                    reader.close();

                } catch (IOException e1) {

                }

            }

        }

    }

    /**

     * 以行为单位读取文件,常用于读面向行的格式化文件

     */

    public static void readFileByLines(String fileName) {

        File file = new File(fileName);

        BufferedReader reader = null;

        try {

            System.out.println(“以行为单位读取文件内容,一次读一整行:”);

            reader = new BufferedReader(new FileReader(file));

            String tempString = null;

            int line = 1;

            // 一次读入一行,直到读入null为文件结束

            while ((tempString = reader.readLine()) != null) {

                // 显示行号

                System.out.println(“line ” + line + “: ” + tempString);

                line++;

            }

            reader.close();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (reader != null) {

                try {

                    reader.close();

                } catch (IOException e1) {

                }

            }

        }

    }

    /**

     * 随机读取文件内容

     */

    public static void readFileByRandomAccess(String fileName) {

        RandomAccessFile randomFile = null;

        try {

            System.out.println(“随机读取一段文件内容:”);

            // 打开一个随机访问文件流,按只读方式

            randomFile = new RandomAccessFile(fileName, “r”);

            // 文件长度,字节数

            long fileLength = randomFile.length();

            // 读文件的起始位置

            int beginIndex = (fileLength  4) ? 4 : 0;

            // 将读文件的开始位置移到beginIndex位置。

            randomFile.seek(beginIndex);

            byte[] bytes = new byte[10];

            int byteread = 0;

            // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。

            // 将一次读取的字节数赋给byteread

            while ((byteread = randomFile.read(bytes)) != -1) {

                System.out.write(bytes, 0, byteread);

            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (randomFile != null) {

                try {

                    randomFile.close();

                } catch (IOException e1) {

                }

            }

        }

    }

    /**

     * 显示输入流中还剩的字节数

     */

    private static void showAvailableBytes(InputStream in) {

        try {

            System.out.println(“当前字节输入流中的字节数为:” + in.available());

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

    public static void main(String[] args) {

        String fileName = “C:/temp/newTemp.txt”;

        ReadFromFile.readFileByBytes(fileName);

        ReadFromFile.readFileByChars(fileName);

        ReadFromFile.readFileByLines(fileName);

        ReadFromFile.readFileByRandomAccess(fileName);

    }

}

原创文章,作者:SYJQ,如若转载,请注明出处:https://www.506064.com/n/134342.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
SYJQSYJQ
上一篇 2024-10-04 00:05
下一篇 2024-10-04 00:05

相关推荐

  • Java JsonPath 效率优化指南

    本篇文章将深入探讨Java JsonPath的效率问题,并提供一些优化方案。 一、JsonPath 简介 JsonPath是一个可用于从JSON数据中获取信息的库。它提供了一种DS…

    编程 2025-04-29
  • java client.getacsresponse 编译报错解决方法

    java client.getacsresponse 编译报错是Java编程过程中常见的错误,常见的原因是代码的语法错误、类库依赖问题和编译环境的配置问题。下面将从多个方面进行分析…

    编程 2025-04-29
  • Java腾讯云音视频对接

    本文旨在从多个方面详细阐述Java腾讯云音视频对接,提供完整的代码示例。 一、腾讯云音视频介绍 腾讯云音视频服务(Cloud Tencent Real-Time Communica…

    编程 2025-04-29
  • Java Bean加载过程

    Java Bean加载过程涉及到类加载器、反射机制和Java虚拟机的执行过程。在本文中,将从这三个方面详细阐述Java Bean加载的过程。 一、类加载器 类加载器是Java虚拟机…

    编程 2025-04-29
  • Java Milvus SearchParam withoutFields用法介绍

    本文将详细介绍Java Milvus SearchParam withoutFields的相关知识和用法。 一、什么是Java Milvus SearchParam without…

    编程 2025-04-29
  • vue下载无后缀名的文件被加上后缀.txt,有后缀名的文件下载正常问题的解决

    本文旨在解决vue下载无后缀名的文件被加上后缀.txt,有后缀名的文件下载正常的问题,提供完整的代码示例供参考。 一、分析问题 首先,需了解vue中下载文件的情况。一般情况下,我们…

    编程 2025-04-29
  • 如何在Java中拼接OBJ格式的文件并生成完整的图像

    OBJ格式是一种用于表示3D对象的标准格式,通常由一组顶点、面和纹理映射坐标组成。在本文中,我们将讨论如何将多个OBJ文件拼接在一起,生成一个完整的3D模型。 一、读取OBJ文件 …

    编程 2025-04-29
  • Python程序文件的拓展

    Python是一门功能丰富、易于学习、可读性高的编程语言。Python程序文件通常以.py为文件拓展名,被广泛应用于各种领域,包括Web开发、机器学习、科学计算等。为了更好地发挥P…

    编程 2025-04-29
  • 为什么用cmd运行Java时需要在文件内打开cmd为中心

    在Java开发中,我们经常会使用cmd在命令行窗口运行程序。然而,有时候我们会发现,在运行Java程序时,需要在文件内打开cmd为中心,这让很多开发者感到疑惑,那么,为什么会出现这…

    编程 2025-04-29
  • Python中读入csv文件数据的方法用法介绍

    csv是一种常见的数据格式,通常用于存储小型数据集。Python作为一种广泛流行的编程语言,内置了许多操作csv文件的库。本文将从多个方面详细介绍Python读入csv文件的方法。…

    编程 2025-04-29

发表回复

登录后才能评论