java实习生面试题|java基础入门之IO文件操作

时间:2019-01-23  来源:基础入门  阅读:

Java的读文件和写文件都是基于字符流的,主要用到下面的几个类:

1、FileReader----读取字符流

2、FileWriter----写入字符流

3、BufferedReader----缓冲指定文件的输入

该类的方法有:

void close()  关闭该流。

void mark(int readAheadLimit)  标记流中的当前位置。

boolean markSupported()  判断此流是否支持 mark() 操作(它一定支持)

int read() 读取单个字符。

int read(char[] cbuf, int off, int len)  将字符读入数组的某一部分。

String readLine()  读取一个文本行。

boolean ready()  判断此流是否已准备好被读取。

void reset() 将流重置为最新的标记。

long skip(long n)  跳过字符。

4、BufferedWriter----将缓冲对文件的输出

该类的方法有:

void close()  关闭该流。

void flush()  刷新该流的缓冲。

void newLine()  写入一个行分隔符。

void write(char[] cbuf, int off, int len)  写入字符数组的某一部分。

void write(int c)  写入单个字符。

void write(String s, int off, int len) 写入字符串的某一部分。


创建和删除文件

下面的代码片段向你展示的是用 Files.createFile (Path target) 方法创建文件的基本用法。

 代码如下


Path target = Paths.get ("D:BackupMyStuff.txt");  

Path file = Files.createFile (target);

  很多时候,出于安全的原因,你可能希望在创建的文件上设置一下属性,例如:是否可读/可写/写执行。这些属性依赖于文件系统的种类,你需要使用跟文件系统相应的权限辅助类来完成这种操作。例如,PosixFilePermission和PosixFilePermissions 为 POSIX 文件系统设计的。下面的是在 POSIX 文件系统上的文件设置读写权限的用法。

 代码如下
Path target = Paths.get ("D:BackupMyStuff.txt");Set perms = PosixFilePermissions.fromString ("rw-rw-rw-");FileAttribute> attr = PosixFilePermissions.asFileAttribute (perms);Files.createFile (target, attr);

 

这个 java.nio.file.attribute 包里提供了很多关于 FilePermission 的类。

  警告 当创建一个带有权限属性的文件时,请注意包含这个文件的文件夹是否有权限的强制约束。例如,你会发现,由于这些限制,尽管你给创建的文件指定了 rw-rw-rw 权限,实际创建的结果却是 rw-r–r– 。

删除文件更简单,使用 Files.delete (Path) 这个方法。

 

 代码如下 Path target = Paths.get ("D:BackupMyStuff.txt");  Files.delete (target);

 

拷贝和移动文件

下面的代码向你展示的是使用 Files.copy (Path source, Path target) 方法做文件拷贝的基本用法。

 代码如下


Path source = Paths.get ("C:My DocumentsStuff.txt");
Path target = Paths.get ("D:BackupMyStuff.txt");Files.copy (source, target);

经常的,在拷贝文件的过程中你可能希望指定一些操作设置。在 Java7 里,你可以通过使用StandardCopyOption enum 来设置这些属性。下面看一个例子。

 代码如下
import static java.nio.file.StandardCopyOption.*;  
Path source = Paths.get ("C:My DocumentsStuff.txt");  
Path target = Paths.get ("D:BackupMyStuff.txt");  
Files.copy (source, target, REPLACE_EXISTING);

 

拷贝操作时可以使用的属性还包括COPY_ATTRIBUTES (保留文件属性) 和 ATOMIC_MOVE(确保移动事务操作的成功,否则进行回滚)。

  移动文件的操作跟拷贝很相似,使用 Files.move (Path source, Path target) 方法。

  同样,你也可以指定移动操作的属性,使用 Files.move (Path source, Path target, CopyOptions...) 方法里的参数来设置。

 代码如下


 import static java.nio.file.StandardCopyOption.*;
Path source = Paths.get ("C:My DocumentsStuff.txt");
Path target = Paths.get ("D:BackupMyStuff.txt");Files.move (source, target, REPLACE_EXISTING, COPY_ATTRIBUTES);

例子

这里主要介绍按行读取的文件操作和写入

 代码如下


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
 
public class JavaFile {
      public static void main(String[] args) {
            try {
            // read file content from file
            StringBuffer sb= new StringBuffer("");
           
            FileReader reader = new FileReader("c://test.txt");
            BufferedReader br = new BufferedReader(reader);
           
            String str = null;
           
            while((str = br.readLine()) != null) {
                  sb.append(str+"/n");
                 
                  System.out.println(str);
            }
           
            br.close();
            reader.close();
           
            // write string to file
            FileWriter writer = new FileWriter("c://test2.txt");
            BufferedWriter bw = new BufferedWriter(writer);
            bw.write(sb.toString());
           
            bw.close();
            writer.close();
      }
      catch(FileNotFoundException e) {
                  e.printStackTrace();
            }
            catch(IOException e) {
                  e.printStackTrace();
            }
      }
 

}

再看一些java文件处理例子

1、文件拷贝

 代码如下

try {
            File inputFile = new File(args[0]);
            if (!inputFile.exists()) {
                System.out.println("源文件不存在,程序终止");
                System.exit(1);
            }
            File outputFile = new File(args[1]);
            InputStream in = new FileInputStream(inputFile);
            OutputStream out = new FileOutputStream(outputFile);
            byte date[] = new byte[1024];
            int temp = 0;
            while ((temp = in.read(date)) != -1) {
                out.write(date);
            }
            in.close();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

 2、java读文件:实现统计某一目录下每个文件中出现的字母个数、数字个数、空格个数及行数,除此之外没有其他字符

 代码如下

String fileName = "D:/date.java.bak";
        // String fileName = "D:/test.qqq";
        String line;
        int i = 0, j = 0, f = 0, k = 0;
        try {
            BufferedReader in = new BufferedReader(new FileReader(fileName));
            line = in.readLine();
            while (line != null) {
                // System.out.println(line);
                char c[] = line.toCharArray();
                for (int i1 = 0; i1 < c.length; i1++) {
                    // 如果是字母
                    if (Character.isLetter(c[i1]))
                        i++;
                    // 如果是数字
                    else if (Character.isDigit(c[i1]))
                        j++;
                    // 是空格
                    else if (Character.isWhitespace(c[i1]))
                        f++;
                }
                line = in.readLine();
                k++;
            }
            in.close();
            System.out
                    .println("字母:" + i + ",数字:" + j + ",空格:" + f + ",行数:" + k);
        } catch (IOException e) {
            e.printStackTrace();
        }

3、 从文件(d:test.txt)中查出字符串”aa”出现的次数

 代码如下

try {
            BufferedReader br = new BufferedReader(new FileReader(
                    "D:\test.txt"));
            StringBuilder sb = new StringBuilder();
            while (true) {
                String str = br.readLine();
                if (str == null)
                    break;
                sb.append(str);
            }
            Pattern p = Pattern.compile("aa");
            Matcher m = p.matcher(sb);
            int count = 0;
            while (m.find()) {
                count++;
            }
            System.out.println(""aa"一共出现了" + count + "次");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

4、 三种方法读取文件

 代码如下

try {
            // 方法一
            BufferedReader br = new BufferedReader(new FileReader(new File(
                    "D:\1.xls")));
            // StringBuilder bd = new StringBuilder();
            StringBuffer bd = new StringBuffer();
            while (true) {
                String str = br.readLine();
                if (str == null) {
                    break;
                }
                System.out.println(str);
                bd.append(str);
            }
            br.close();
            // System.out.println(bd.toString());
            // 方法二
            InputStream is = new FileInputStream(new File("d:\1.xls"));
            byte b[] = new byte[Integer.parseInt(new File("d:\1.xls").length()
                    + "")];
            is.read(b);
            System.out.write(b);
            System.out.println();
            is.close();
            // 方法三
            Reader r = new FileReader(new File("d:\1.xls"));
            char c[] = new char[(int) new File("d:\1.xls").length()];
            r.read(c);
            String str = new String(c);
            System.out.print(str);
            r.close();
        } catch (RuntimeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

5、三种方法写文件

 代码如下

try {
            PrintWriter pw = new PrintWriter(new FileWriter("d:\1.txt"));
            BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
                    "d:\1.txt")));
            OutputStream os = new FileOutputStream(new File("d:\1.txt"));
            // 1
            os.write("ffff".getBytes());
            // 2
            // bw.write("ddddddddddddddddddddddddd");
            // 3
            // pw.print("你好sssssssssssss");
            bw.close();
            pw.close();
            os.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

6、读取文件,并把读取的每一行存入double型数组中

 代码如下

try {
            BufferedReader br = new BufferedReader(new FileReader(new File(
                    "d:\2.txt")));
            StringBuffer sb = new StringBuffer();
            while (true) {
                String str = br.readLine();
                if (str == null) {
                    break;
                }
                sb.append(str + "、");
            }
            String str = sb.toString();
            String s[] = str.split("、");
            double d[] = new double[s.length];
            for (int i = 0; i < s.length; i++) {
                d[i] = Double.parseDouble(s[i]);
            }
            for (int i = 0; i < d.length; i++) {
                System.out.println(d[i]);
            }
            br.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

java实习生面试题|java基础入门之IO文件操作

http://m.bbyears.com/asp/47481.html

推荐访问:sql基础面试题及答案
相关阅读 猜你喜欢
本类排行 本类最新