1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容

4、随机读取文件内容


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);
    }
}

5、将内容追加到文件尾部


public class AppendToFile {
    /**
     * A方法追加文件:使用RandomAccessFile
     */
    public static void appendMethodA(String fileName, String content) {
        try {
            // 打开一个随机访问文件流,按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度,字节数
            long fileLength = randomFile.length();
            //将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.writeBytes(content);
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }     /**
     * B方法追加文件:使用FileWriter
     */
    public static void appendMethodB(String fileName, String content) {
        try {
            //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  
 
  // 防止中文乱码
  
try
{
//打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
// FileWriter writer = new FileWriter(fileName, true); Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName,true), "UTF-8"));
writer.write(line);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}     public static void main(String[] args) {
        String fileName = "C:/temp/newTemp.txt";
        String content = "new append!";
        //按方法A追加文件
        AppendToFile.appendMethodA(fileName, content);
        AppendToFile.appendMethodA(fileName, "append end. \n");
        //显示文件内容
        ReadFromFile.readFileByLines(fileName);
        //按方法B追加文件
        AppendToFile.appendMethodB(fileName, content);
        AppendToFile.appendMethodB(fileName, "append end. \n");
        //显示文件内容
        ReadFromFile.readFileByLines(fileName);
    }
}

java对文件的操作的更多相关文章

  1. loadrunner 脚本开发-调用java jar文件远程操作Oracle数据库测试

    调用java jar文件远程操作Oracle数据库测试 by:授客 QQ:1033553122 测试环境 数据库:linux 下Oracle_11g_R2 Loadrunner:11 备注:想学ora ...

  2. Java的文件读写操作

    file(内存)----输入流---->[程序]----输出流---->file(内存) 当我们读写文本文件的时候,采用Reader是非常方便的,比如FileReader,InputStr ...

  3. Java的文件读写操作 <转>

    目录: file内存----输入流----程序----输出流----file内存 java中多种方式读文件 判断文件是否存在不存在创建文件 判断文件夹是否存在不存在创建文件夹 java 写文件的三种方 ...

  4. [转]Java的文件读写操作

    file(内存)----输入流---->[程序]----输出流---->file(内存) 当我们读写文本文件的时候,采用Reader是非常方便的,比如FileReader,InputStr ...

  5. java大文件读写操作,java nio 之MappedByteBuffer,高效文件/内存映射

    java处理大文件,一般用BufferedReader,BufferedInputStream这类带缓冲的Io类,不过如果文件超大的话,更快的方式是采用MappedByteBuffer. Mapped ...

  6. java 实现文件读写操作

    import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /* JAVA IO 读写操作 20 ...

  7. Java 对文件的操作

    public class ReadFile { /** * 按行读取文件操作 * @throws IOException */ public void readFile(String fileName ...

  8. java写文件读写操作(IO流,字节流)

    package copyfile; import java.io.*; public class copy { public static void main(String[] args) throw ...

  9. java 的文件读取操作

    /** * @param filePath 文件的全路径 * 返回我们读取到的文件内容 * **/ public static String readFile(String filePath) { F ...

  10. java写文件读写操作(IO流,字符流)

    package copyfile; import java.io.*; public class copy { public static void main(String[] args) throw ...

随机推荐

  1. R包安装的正确方式

    options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) if(! req ...

  2. springboot-web进阶(三)——统一异常处理

    补充 springboot中也是一样的可以对结果进行统一格式的包装,这样也就方便了前台的统一接收处理了: 1.结果集包装类 package com.example.demo.bean; /** * 结 ...

  3. win10操作系统vs2010编译osg3.4.0问题解决记录

    参考博客:OSG3.4.0+VS2010+WIN10编译及二次开发环境搭建 链接:https://blog.csdn.net/hsc1239653453/article/details/7827856 ...

  4. JavaScript总结(六)

    使用DOM操纵样式表 ✍ 操纵元素的Style样式属性(所有的均对于CSS的内联式) 对于每个CSS样式,Style对象都包含了一个相对应的属性,只需要用到style属性即可: Div.style.c ...

  5. PostgreSQL的autovacuum 与 vacuum full

    磨砺技术珠矶,践行数据之道,追求卓越价值 回到上一级页面:PostgreSQL内部结构与源代码研究索引页    回到顶级页面:PostgreSQL索引页 作者 高健@博客园  luckyjackgao ...

  6. PyQt5 笔记(02):嵌套布局

    如前一篇笔记,我们还是只讨论两层嵌套布局的情况. 前面的布局有一个缺点:有三个内层布局,则需要三个空部件.那若有十个内层布局呢?显然会让人不舒服. 刚才在玩 Qt Designer 时,发现了一个更好 ...

  7. Openstack入门篇(十)之nova服务(计算节点)的部署与测试

    1.安装服务软件包 [root@linux-node2 ~]# yum install -y centos-release-openstack-newton [root@linux-node2 ~]# ...

  8. 菜鸟vimer成长记——第2.4章、cmd-line模式

    cmd-line模式又有3个类型:Ex 命令(ex commands).查找模式(Search patterns).Filter 命令(Filter commands).本文主要重点的是Ex 命令和S ...

  9. avascript小技巧

    avascript小技巧 事件源对象 event.srcElement.tagName event.srcElement.type 捕获释放 event.srcElement.setCapture() ...

  10. python将oracle中的数据导入到mysql中。

    一.导入表结构.使用工具:navicate premium 和PowerDesinger 1. 先用navicate premium把oracle中的数据库导出为oracle脚本. 2. 在Power ...