zoukankan      html  css  js  c++  java
  • java读写文件

    import java.io.*;

    public class Demo {
    public static void main(String[] args) {
    try {
    // 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw
    String pathname = "F:/input.txt";
    InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(pathname))); // 建立一个输入流对象reader
    BufferedReader br = new BufferedReader(reader); // 建立一个对象,它把文件内容转成计算机能读懂的语言
    /* 写入Txt文件 */
    File writename = new File("F:/output.txt");
    if (writename.exists()) {
    writename.delete();
    }
    writename.createNewFile(); // 创建新文件
    BufferedWriter out = new BufferedWriter(new FileWriter(writename));
    String line = null;
    while ((line = br.readLine()) != null) {
    out.write(line + " "); // 即为换行
    }
    out.flush(); // 把缓存区内容压入文件
    out.close(); // 最后记得关闭文件
    br.close();
    reader.close();

    } catch (Exception e) {
    e.printStackTrace();
    }

    }
    }

    //同过判断文件的结尾来读取文件   
    import java.io.File;   
    import java.io.InputStream;   
    import java.io.FileInputStream;   
    public class InputStreamDemo02   
    {   
        public static void main(String args[]) throws Exception{   
            File f = new File("E:"+File.separator+"java2"+File.separator+"StreamDemo"+File.separator+"test.txt");   
            InputStream in = new FileInputStream(f);   
            byte b[] = new byte[1024];   
            int len = 0;   
            int temp=0;          //所有读取的内容都使用temp接收   
            while((temp=in.read())!=-1){    //当没有读取完时,继续读取   
                b[len]=(byte)temp;   
                len++;   
            }   
            in.close();   
            System.out.println(new String(b,0,len));   
        }   
  • 相关阅读:
    _MSC_VER
    git之撤销修改
    vi/vim如何添加或删除多行注释
    C++ 读取文件数据和输出数据到文件
    git上传本地单独修改的文件
    Git学习笔记
    C++中类的声明
    linux中ldconfig的使用介绍
    #define 和 typedef 中的##
    find、xargs、grep基本用法
  • 原文地址:https://www.cnblogs.com/cxhfuujust/p/9907736.html
Copyright © 2011-2022 走看看