让Java程序谨慎的出错

版权声明:转载请注明出处 https://blog.csdn.net/github_37412255/article/details/80143774

在实现Java某个函数时,首先要做的工作是对函数参数的检查。这一步工作主要是找出参数对该函数来说潜在的错误。尤其是对于引用类型参数来说,如果它指向的内存空间无任何对象,则函数接下来所有对参数的操作都是无效的。因此检查理论上是必须的。检查通常是抛异常类。

但是也有例外的情况(不抛异常的情况)。如果我们并不希望程序就此被中断,以错误的形式输出的控制台。我们希望以更加友好、“自满”的形式输出到控制台,我们该怎么做呢?

很简单,做判空的操作,如果参数为空,则参数级联的所有操纵开关都关闭。

就像这个例子:

package facvisual;

import java.io.*;
import java.nio.file.*;
import java.util.*;

/**
 * The tool class: the encapsulation of common functions.
 * @author Long weibing
 * @since 2018.04.29
 */
public class Utils {

    public static void main(String[] args) {
        String curPath = "E:\\";
        List<String> namesResult = Utils.allFiles(curPath);
        System.out.println("The numbers of all files: " + namesResult.size());
        for (String name : namesResult) {
            System.out.println(name);
        }
    }

    /**
     * Collecting all files absolute pathname under 'path' path
     * <font color="red">(No directories are included)</font>.
     * @param path Search path
     * @return List<String> A collection of String type
     */
    public static List<String> allFiles(String path) {
        // The collection of all files absolute pathname.
        List<String> output = new LinkedList<String>();
        // Collect temporary files and directories.
        Stack<File> stack = new Stack<File>();
        stack.push(Arrays.asList(new File(path).listFiles()));
        while (!stack.isEmpty()) {
            File curFile = stack.pop();
            String curEleAbsPath = curFile.toString();
            // It's a directory
            boolean isDir = Files.isDirectory(Paths.get(curEleAbsPath));
            if (isDir) {
                List<File> temp = null;
                if (curFile.listFiles() != null) {
                    temp = Arrays.asList(curFile.listFiles());
                }
                if (temp != null) {
                    stack.push(temp);
                }                
            } else {
                // Collect a file.
                output.add(curEleAbsPath);
            }
        }
        return output;
    }
}

该程序需要另外一个类Stack

package facvisual;

import java.util.*;

/**
 * stack: A data structure
 * @author Weibing Long
 * @since 2018.04.16
 * @param <Item> 
 */
public class Stack<Item> {
    private Node root;
    private int n;

    /**
     * push a element
     * @param item element
     */
    public void push(Item item) {
        if (item == null)
            throw new NullPointerException("item mush be not null!");
        if (root == null) {
            root = new Node();
            root.item = item;
            root.next = root;
        } else {
            Node temp = root;
            root = new Node();
            root.item = item;
            root.next = temp;
        }
        n++;
    }

    /**
     * push all elements in List.
     * @param items elements
     */
    public void push(List<Item> items) {
        for (Item item : items) {
            this.push(item);
        }
    }

    /**
     * 
     * @return pop a element
     */
    public Item pop() {
        if (n == 0)
            throw new NullPointerException("The stack not any element!");
        Item item = root.item;
        root = root.next;
        n--;
        return item;
    }

    /**
     * 
     * @return The numbers of element
     */
    public int size() {
        return n;
    }

    public boolean isEmpty() {
        return n == 0;
    }

    private class Node {
        private Item item;
        private Node next;  
    }

    /**
     * According to pop stack order.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        Node tempRoot = root;
        for (int i = 0; i < size(); i++) {
            sb.append(tempRoot.item);
            if (i < size() - 1) {
                sb.append(", ");
            }
            tempRoot = tempRoot.next;
        }
        sb.append("]");
        return sb.toString();
    }
}

这个例子输出当前路径下(代码体现在 String curPath = "E:\\";)的所有文件的绝对路径名(不包括文件夹)。在执行Arrays.asList(curFile.listFiles())代码时,可能由于curFile.listFiles()为空(当File对象代表某个文件,而不是目录时),而导致其出错,所以应该改为

List<File> temp = null;
if (curFile.listFiles() != null) {
    temp = Arrays.asList(curFile.listFiles());
}

保证了代码正常执行。

猜你喜欢

转载自blog.csdn.net/github_37412255/article/details/80143774