• Java读取文件


    基本方法:

    String filePath="D:\test\abc.txt";
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
      String data = null;
      while((data = br.readLine())!=null)
      {
       System.out.println(data); 
      }
    br.close()

    若要指定文件的字符编码来读取,则需要使用InputStreamReader的另一个构造函数,加上字符编码:

    //说明文件的编码为GB2312字符集
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"GB2312"));
    //说明文件的编码为UTF-8字符集
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"UTF-8"));

    写入数据:

    public static void write(String filePath, String data)
        {
            try
            {
                File file = new File(filePath);
                if (!file.exists())
                {
                    file.createNewFile();
                }
                else
                {
                    FileOutputStream out = new FileOutputStream(file, true);
                    byte[] bt = data.getBytes("utf-8");
                    out.write(bt);
                    //以下代码用于追加换行符
                    byte[] c = new byte[2];
                    c[0] = 0x0d;
                    c[1] = 0x0a;// 用于输入换行符的字节码
                    String t = new String(c);
                    out.write(t.getBytes("utf-8"));
                    out.close();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }

    关于字符编码,即其他读取、写入、追加、保存操作,待续

  • 相关阅读:
    AD域渗透测试笔记
    ctf之WEB练习一
    CTF之crpto练习三
    ctf之WEB练习二
    ctf之WEB练习三
    [转]Ant学习笔记——自己构建Ant编译环境
    [转]【NoSQL】NoSQL入门级资料整理(CAP原理、最终一致性)
    啥叫异步调用
    C++中虚函数的作用是什么?它应该怎么用呢?
    [转]Thrift连接池实现
  • 原文地址:https://www.cnblogs.com/aaronhoo/p/5253291.html
Copyright © 2020-2023  润新知