• java文件读写


    实现内容:打开文件并判断文件是否存在,如果存在就打开文件并把文件内容输出到控制台,之后把文件内容输出到另外一个文件

    过程所需基础:

    1、判断文件存不存在

    String filePth= "D:\bh\key\rsa_public_key.pem";
    File file = new File(filePth);
    if(!file.exists()){
    // 文件不存在
    throw new RuntimeException("文件不存在");
    }

    2、文件打开输入输出时需要捕捉异常

    更多可见:https://www.runoob.com/java/java-exceptions.html

    try {
        file = new FileInputStream(fileName);
        x = (byte) file.read();
    } catch(IOException i) {
        i.printStackTrace();
        return -1;
    }

    3、Java字符输出流

    // (1)方法介绍:
    //   int read() * 读取单个字符
    //   int read(char[] cbuf) * 将字符读入数组
    //   abstract int read(char[] cbuf, int off, int len) * 将字符读入数组的某一部分。
    // 代码实现:
    import java.io.FileReader;
    import java.io.IOException;
     
    public class FileReaderDemo {
     
        public static void main(String[] args) throws IOException{
            // TODO Auto-generated method stub
            FileReader fr = new FileReader("d://input.txt");
            int hasRead = 0;
            while((hasRead = fr.read())!=-1){
                System.out.print((char)hasRead);
            }
            fr.close();
        }
     
    }

    4、Java字符输入流

    //方法介绍:
    //  void write(int c):写入单个字符。
    //  void write(String str):写入字符串。
    //  void write(String str, int off, int len):写入字符串的某一部分。
    //  void write(char[] cbuf):写入字符数组。
    //  abstract void write(char[] cbuf, int off, int len):写入字符数组的某一部分。
    //代码实现:
     
    import java.io.FileWriter;
    import java.io.IOException;
     
    public class FileWriterDemo {
     
        public static void main(String[] args) throws IOException{
            // TODO Auto-generated method stub
            FileWriter fw = new FileWriter("d://filewriter.txt");
            fw.write("123");
            //必须要加fw.flush(),代表刷新,不加这个语句不能写入到文件中
            fw.flush();
            fw.close();
        }
     
    }

    5、写入文件按照追加方式

    FileWriter(String filename,boolean append)方法中
    append参数指的是boolean的值,如果append的值是true,则将数据写入文件末尾处,而不是写入文件开始处。

    6、不要使用==来判断两个字符串是否相等

    java中字符串的比较:==
    我们经常习惯性的写上if(str1==str2),这种写法在java中可能会带来问题

    example1:
    String a="abc";
    String b="abc"

    那么a==b将返回true。因为在java中字符串的值是不可改变的,相同的字符串在内存中只会存

    一份,所以a和b指向的是同一个对象;

    example2:
    String a=new String("abc"); 
    String b=new String("abc");

    那么a==b将返回false,此时a和b指向不同的对象。
    2、用equals方法比较的是字符串的内容是否相同

    example:
    String a=new String("abc"); 
    String b=new String("abc");
    a.equals(b);

    众所周知,按照字符读写数据会导致有些文件不能读写失败(比如音频文件,你使用字符读写之后这个文件再按照音频格式就会打开失败)

    按照字节读取数据可以读取所有文件,如果想要看字节读取数据可看:https://www.cnblogs.com/liuzengzhi/p/11826177.html

    总代码:

    import java.io.FileWriter;
    import java.io.FileReader;
    import java.io.File;
    import java.io.IOException;
    import java.util.Scanner;
    
    public class qmh {
        public static String open_file(Scanner scan,File file)
        {
            //E:/1.txt
            System.out.println("请输入文件路径和名称:");
            String s = scan.nextLine();
            String suffix[] = s.split("\.");
            System.out.println(suffix[1]);
            /*
             * java中字符串的比较:==
            我们经常习惯性的写上if(str1==str2),这种写法在java中可能会带来问题
            example1:
            String a="abc";
            String b="abc"
            那么a==b将返回true。因为在java中字符串的值是不可改变的,相同的字符串在内存中只会存
            
            一份,所以a和b指向的是同一个对象;
            example2:
            String a=new String("abc"); 
            String b=new String("abc");
            那么a==b将返回false,此时a和b指向不同的对象。
            2、用equals方法比较的是字符串的内容是否相同
            example:
            String a=new String("abc"); 
            String b=new String("abc");
             a.equals(b);
             * */
            if(suffix[1].equals("txt"));
            else 
            {
                System.out.println("文件后缀名输入错误!");
                return "";
            }
            try {
                file = new File(s);
                if (!file.exists()) {
                    System.out.println("找不到文件!");
                      return "";
                }
                else {
                    System.out.println("打开文件成功!");
                    return s;
                }
            }catch(Exception i){
                i.printStackTrace();
            }
            return "";
        }
        public static void file_input(FileReader fr,FileWriter fw,String os)
        {
            int hasRead = 0;
            try {
                fr = new FileReader(os);
                while((hasRead = fr.read())!=-1){
                    System.out.print((char)hasRead);
                    file_output(fw,(char)hasRead);
                }
                fr.close();
            }catch(IOException i) {
                i.printStackTrace();
            }
        }
        public static void file_output(FileWriter fw,char s)
        {
            try {
                fw = new FileWriter("E://2.txt",true);
                fw.write(s);
                //必须要加fw.flush(),代表刷新,不加这个语句不能写入到文件中
                fw.flush();
                fw.close();
            }catch(IOException i) {
                i.printStackTrace();
            }
        }
        public static void main(String args[]) {
            Scanner scan = new Scanner(System.in);
            FileReader fr=null;
            FileWriter fw=null;
            File file=null;
            String os;
            os=open_file(scan,file);
            if(os!="") {
                file_input(fr,fw,os);
            }
        }
    }
  • 相关阅读:
    Java代码输出是“father”还是“child”(二)
    Java代码输出是“father”还是“child”(一)
    “var arr = []; ”和 “var arr = {};” 的区别
    Servlet页面间对象传递的方法
    利用OWI优化SQL
    Oracle 12c 12.1.0.1.0管理控制文件官方文档说明
    计算工资
    检测本地网络连接状态断开以及恢复的方法
    linux 批量创建用户
    比较两表数据
  • 原文地址:https://www.cnblogs.com/kongbursi-2292702937/p/13957055.html
Copyright © 2020-2023  润新知