自学内容网 自学内容网

java菜鸟学习实例(三)

Java实例

七.Java 目录操作

1.Java 实例 - 递归创建目录

import java.io.File;
 
public class Main {
    public static void main(String[] args) {
        String directories = "D:\\a\\b\\c\\d\\e\\f\\g\\h\\i";
        File file = new File(directories);
        boolean result = file.mkdirs();
        System.out.println("Status = " + result);
    }
}

2.Java 实例 - 删除目录

import java.io.File;
 
public class Main {
    public static void main(String[] argv) throws Exception {
        // 删除当前目录下的 test 目录
        deleteDir(new File("./test"));
    }
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir
                (new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        if(dir.delete()) {
            System.out.println("目录已被删除!");
            return true;
        } else {
            System.out.println("目录删除失败!");
            return false;
        }
    }
}

3.Java 实例 - 判断目录是否为空

import java.io.File;
 
public class Main
{
    public static void main(String[] args)
    {
        File file = new File("./testdir");  // 当前目录下的 testdir目录
        if(file.isDirectory()){
            if(file.list().length>0){
                System.out.println("目录不为空!");
            }else{
                System.out.println("目录为空!");
            }
        }else{
            System.out.println("这不是一个目录!");
        }
    }
}

4.Java 实例 - 判断文件是否隐藏

import java.io.File;
 
public class Main {
    public static void main(String[] args) {
        File file = new File("C:/Demo.txt");
        System.out.println(file.isHidden());
    }
}

5.Java 实例 - 获取目录大小

import java.io.File;
import org.apache.commons.io.FileUtils;
 
public class Main {
    public static void main(String[] args) {
        long size = FileUtils.sizeOfDirectory(new File("C:/test"));
        System.out.println("Size: " + size + " bytes");
    }
}

6.Java 实例 - 在指定目录中查找文件

import java.io.File;
 
public class Main {
    public static void main(String[] argv) throws Exception {
        File dir = new File("../java");
        String[] children = dir.list();
        if (children == null) {
            System.out.println("该目录不存在");
        }
        else {
            for (int i = 0; i < children.length; i++) {
                String filename = children[i];
                System.out.println(filename);
            }
        }
    }
}

7.Java 实例 - 获取文件的上级目录

import java.io.File;
 
public class Main {
    public static void main(String[] args) {
        File file = new File("C:/File/demo.txt");
        String strParentDirectory = file.getParent();
        System.out.println("文件的上级目录为 : " + strParentDirectory);
    }
}

8.Java 实例 - 获取目录最后修改时间

import java.io.File;
import java.util.Date;
 
public class Main {
    public static void main(String[] args) {
        File file = new File("C://FileIO//demo.txt");
        System.out.println("最后修改时间:" + new Date(file.lastModified()));
    }
}

9.Java 实例 - 打印目录结构

import java.io.File;
import java.io.IOException;
 
public class FileUtil {
    public static void main(String[] a)throws IOException{
        showDir(1, new File("d:\\Java"));
    }
    static void showDir(int indent, File file) throws IOException {
        for (int i = 0; i < indent; i++)
            System.out.print('-');
        System.out.println(file.getName());
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++)
                showDir(indent + 4, files[i]);
        }
    }
}

10.Java 实例 - 遍历指定目录下的所有目录

import java.io.*;
 
class Main {
   public static void main(String[] args) {
      File dir = new File("F:");
      File[] files = dir.listFiles();
      FileFilter fileFilter = new FileFilter() {
         public boolean accept(File file) {
            return file.isDirectory();
         }
      };
      files = dir.listFiles(fileFilter);
      System.out.println(files.length);
      if (files.length == 0) {
         System.out.println("目录不存在或它不是一个目录");
      }
      else {
         for (int i=0; i< files.length; i++) {
            File filename = files[i];
            System.out.println(filename.toString());
         }
      }
   }
}

11.Java 实例 - 遍历指定目录下的所有文件

import java.io.File;
 
class Main {
    public static void main(String[] args) {
        File dir = new File("C:");
        String[] children = dir.list();
        if (children == null) {
            System.out.println( "目录不存在或它不是一个目录");
        }
        else {
            for (int i=0; i< children.length; i++) {
                String filename = children[i];
                System.out.println(filename);
            }
        }
    }
}

12.Java 实例 - 在指定目录中查找文件

import java.io.*;
 
class Main {
   public static void main(String[] args) {
      File dir = new File("C:");
      FilenameFilter filter = new FilenameFilter() {
         public boolean accept
         (File dir, String name) {
            return name.startsWith("b");
        }
      };
      String[] children = dir.list(filter);
      if (children == null) {
         System.out.println("目录不存在或它不是一个目录");
      } 
      else {
         for (int i=0; i < children.length; i++) {
            String filename = children[i];
            System.out.println(filename);
         }
      } 
   }
}

13.Java 实例 - 遍历系统根目录

import java.io.*;
 
class Main{
    public static void main(String[] args){
        File[] roots = File.listRoots();
        System.out.println("系统所有根目录:");
        for (int i=0; i < roots.length; i++) {
            System.out.println(roots[i].toString());
        }
    }
}

14.Java 实例 - 查看当前工作目录

class Main {
    public static void main(String[] args) {
        String curDir = System.getProperty("user.dir");
        System.out.println("你当前的工作目录为 :" + curDir);
    }
}

15.Java 实例 - 遍历目录

import java.io.File;
 
public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println("遍历目录");
        File dir = new File("/www/java"); //要遍历的目录
        visitAllDirsAndFiles(dir);
    }
    public static void visitAllDirsAndFiles(File dir) {
        System.out.println(dir);
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                visitAllDirsAndFiles(new File(dir, children[i]));
            }
        }
    }
}

八.Java 异常处理

1.Java 实例 - 异常处理方法

class ExceptionDemo
{
    public static void main(String[] args) {
        try {
            throw new Exception("My Exception");
        } catch (Exception e) {
            System.err.println("Caught Exception");
            System.err.println("getMessage():" + e.getMessage());
            System.err.println("getLocalizedMessage():" + e.getLocalizedMessage());
            System.err.println("toString():" + e);
            System.err.println("printStackTrace():");
            e.printStackTrace();
        }
    }
}

2.Java 实例 - 多个异常处理(多个catch)

class Demo  
{  
    int div(int a,int b) throws ArithmeticException,ArrayIndexOutOfBoundsException//在功能上通过throws的关键字声明该功能可能出现问题  
    {  
        int []arr = new int [a];  
  
        System.out.println(arr[4]);//制造的第一处异常  
  
        return a/b;//制造的第二处异常  
    }  
}  
  
  
class ExceptionDemo  
{  
    public static void main(String[]args) //throws Exception  
    {  
        Demo d = new Demo();  
  
        try  
            {  
                int x = d.div(4,0);//程序运行截图中的三组示例 分别对应此处的三行代码  
                //int x = d.div(5,0);  
                //int x = d.div(4,1);  
                System.out.println("x="+x);   
        }  
        catch (ArithmeticException e)  
        {  
            System.out.println(e.toString());  
        }  
        catch (ArrayIndexOutOfBoundsException e)  
        {  
            System.out.println(e.toString());  
        }  
        catch (Exception e)//父类 写在此处是为了捕捉其他没预料到的异常 只能写在子类异常的代码后面  
                            //不过一般情况下是不写的   
        {  
            System.out.println(e.toString());  
        }  
          
  
  
        System.out.println("Over");  
    }  
  
}

3.Java 实例 - Finally的用法

public class ExceptionDemo2 {
   public static void main(String[] argv) {
      new ExceptionDemo2().doTheWork();
   }
   public void doTheWork() {
      Object o = null;
      for (int i=0; i<5; i++) {
         try {
            o = makeObj(i);
         }
         catch (IllegalArgumentException e) {
            System.err.println
            ("Error: ("+ e.getMessage()+").");
            return;   
         }
         finally {
            System.err.println("都已执行完毕");
            if (o==null)
            System.exit(0);
        }
        System.out.println(o); 
      }
   }
   public Object makeObj(int type) 
   throws IllegalArgumentException {
      if (type == 1)  
      throw new IllegalArgumentException
      ("不是指定的类型: " + type);
      return new Object();
   }
}

4.Java 实例 - 使用 catch 处理异常

public class Main {
    public static void main (String args[]) {
        int array[]={20,20,40};
        int num1=15,num2=10;
        int result=10;
        try{
            result = num1/num2;
            System.out.println("结果为 " +result);
            for(int i =5;i >=0; i--) {
                System.out.println ("数组的元素值为 " +array[i]);
            }
        }
        catch (Exception e) {
            System.out.println("触发异常 : "+e);
        }
    }
}

5.Java 实例 - 多线程异常处理

class MyThread extends Thread{
    public void run(){
        System.out.println("Throwing in " +"MyThread");
        throw new RuntimeException();
    }
}
class Main {
    public static void main(String[] args){
        MyThread t = new MyThread();
        t.start();
        try{
            Thread.sleep(1000);
        }
        catch (Exception x){
            System.out.println("Caught it" + x);
        }
        System.out.println("Exiting main");
    }
}

6.Java 实例 - 获取异常的堆栈信息

public class Main{
    public static void main (String args[]){
        int array[]={20,20,40};
        int num1=15,num2=10;
        int result=10;
        try{
            result = num1/num2;
            System.out.println("The result is" +result);
            for(int i =5; i>=0; i--) {
                System.out.println("The value of array is" +array[i]);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

7.Java 实例 - 重载方法异常处理

public class Main {
    double method(int i) throws Exception{
        return i/0;
    }
    boolean method(boolean b) {
        return !b;
    }
    static double method(int x, double y) throws Exception  {
        return x + y ;
    }
    static double method(double x, double y) {
        return x + y - 3;
    }   
    public static void main(String[] args) {
        Main mn = new Main();
        try{
            System.out.println(method(10, 20.0));
            System.out.println(method(10.0, 20));
            System.out.println(method(10.0, 20.0));
            System.out.println(mn.method(10));
        }
        catch (Exception ex){
            System.out.println("exception occoure: "+ ex);
        }
    }
}

8.Java 实例 - 链试异常

public class Main {
    public static void main (String args[])throws Exception  {
        int n=20,result=0;
        try{
            result=n/0;
            System.out.println("结果为"+result);
        }
        catch(ArithmeticException ex){
            System.out.println("发算术异常: "+ex);
            try {
                throw new NumberFormatException();
            }
            catch(NumberFormatException ex1) {
                System.out.println("手动抛出链试异常 : "+ex1);
            }
        }
    }
}

9.Java 实例 - 自定义异常

class WrongInputException extends Exception {  // 自定义的类
    WrongInputException(String s) {
        super(s);
    }
}
class Input {
    void method() throws WrongInputException {
        throw new WrongInputException("Wrong input"); // 抛出自定义的类
    }
}
class TestInput {
    public static void main(String[] args){
        try {
            new Input().method();
        }
        catch(WrongInputException wie) {
            System.out.println(wie.getMessage());
        }
    } 
}

九.Java 数据结构

1.Java 实例 – 数字求和运算

public class Main {
    public static void main(String[] args) {
        int limit=100;
        int sum=0;
        int i=1;
        do
        {
            sum=sum+i;
            i++;
        }
        while(i<=limit);
        System.out.println("sum="+sum);
    }
}

2.Java 实例 – 利用堆栈将中缀表达式转换成后缀

import java.io.IOException;
 
public class InToPost {
   private Stack theStack;
   private String input;
   private String output = "";
   public InToPost(String in) {
      input = in;
      int stackSize = input.length();
      theStack = new Stack(stackSize);
   }
   public String doTrans() {
      for (int j = 0; j < input.length(); j++) {
         char ch = input.charAt(j);
         switch (ch) {
            case '+': 
            case '-':
            gotOper(ch, 1); 
            break; 
            case '*': 
            case '/':
            gotOper(ch, 2); 
            break; 
            case '(': 
            theStack.push(ch);
            break;
            case ')': 
            gotParen(ch); 
            break;
            default: 
            output = output + ch; 
            break;
         }
      }
      while (!theStack.isEmpty()) {
         output = output + theStack.pop();
      }
      System.out.println(output);
      return output; 
   }
   public void gotOper(char opThis, int prec1) {
      while (!theStack.isEmpty()) {
         char opTop = theStack.pop();
         if (opTop == '(') {
            theStack.push(opTop);
            break;
         }
         else {
            int prec2;
            if (opTop == '+' || opTop == '-')
            prec2 = 1;
            else
            prec2 = 2;
            if (prec2 < prec1) { 
               theStack.push(opTop);
               break;
            }
            else
            output = output + opTop;
         }
      }
      theStack.push(opThis);
   }
   public void gotParen(char ch){ 
      while (!theStack.isEmpty()) {
         char chx = theStack.pop();
         if (chx == '(') 
         break; 
         else
         output = output + chx; 
      }
   }
   public static void main(String[] args) 
   throws IOException {
      String input = "1+2*4/5-7+3/6";
      String output;
      InToPost theTrans = new InToPost(input);
      output = theTrans.doTrans(); 
      System.out.println("Postfix is " + output + '\n');
   }
   class Stack {
      private int maxSize;
      private char[] stackArray;
      private int top;
      public Stack(int max) {
         maxSize = max;
         stackArray = new char[maxSize];
         top = -1;
      }
      public void push(char j) {
         stackArray[++top] = j;
      }
      public char pop() {
         return stackArray[top--];
      }
      public char peek() {
         return stackArray[top];
      }
      public boolean isEmpty() {
         return (top == -1);
     }
   }
}

3.Java 实例 – 在链表(LinkedList)的开头和结尾

import java.util.LinkedList;
 
public class Main {
    public static void main(String[] args) {
        LinkedList<String> lList = new LinkedList<String>();
        lList.add("1");
        lList.add("2");
        lList.add("3");
        lList.add("4");
        lList.add("5");
        System.out.println(lList);
        lList.addFirst("0");
        System.out.println(lList);
        lList.addLast("6");
        System.out.println(lList);
    }
}

4.Java 实例 – 获取链表(LinkedList)的第一个

import java.util.LinkedList;
 
public class Main {
    public static void main(String[] args) {
        LinkedList<String> lList = new LinkedList<String>();
        lList.add("100");
        lList.add("200");
        lList.add("300");
        lList.add("400");
        lList.add("500");
        System.out.println("链表的第一个元素是:" + lList.getFirst());
        System.out.println("链表的最后一个元素是:" + lList.getLast());
    }
}

5.Java 实例 – 删除链表中的元素

import java.util.*;
 
public class Main {
   public static void main(String[] args) {
      LinkedList<String> lList = new LinkedList<String>();
      lList.add("1");
      lList.add("8");
      lList.add("6");
      lList.add("4");
      lList.add("5");
      System.out.println(lList);
      lList.subList(2, 4).clear();
      System.out.println(lList);
   }
}

6.Java 实例 – 获取链表的元素

import java.util.*;
 
public class Main {
   private LinkedList list = new LinkedList();
   public void push(Object v) {
      list.addFirst(v);
   }
   public Object top() {
      return list.getFirst();
   }
   public Object pop() {
      return list.removeFirst();
   }
   public static void main(String[] args) {
      Main stack = new Main();
      for (int i = 30; i < 40; i++)
         stack.push(new Integer(i));
      System.out.println(stack.top());
      System.out.println(stack.pop());
      System.out.println(stack.pop());
      System.out.println(stack.pop());
   }
}

7.Java 实例 – 获取向量元素的索引值

import java.util.Collections;
import java.util.Vector;
 
public class Main {
   public static void main(String[] args) {
      Vector v = new Vector();
      v.add("X");
      v.add("M");
      v.add("D");
      v.add("A");
      v.add("O");
      Collections.sort(v);
      System.out.println(v);
      int index = Collections.binarySearch(v, "D");
      System.out.println("元素索引值为 : " + index);
   }
}

8.Java 实例 – 栈的实现

]`public class MyStack {
   private int maxSize;
   private long[] stackArray;
   private int top;
   public MyStack(int s) {
      maxSize = s;
      stackArray = new long[maxSize];
      top = -1;
   }
   public void push(long j) {
      stackArray[++top] = j;
   }
   public long pop() {
      return stackArray[top--];
   }
   public long peek() {
      return stackArray[top];
   }
   public boolean isEmpty() {
      return (top == -1);
   }
   public boolean isFull() {
      return (top == maxSize - 1);
   }
   public static void main(String[] args) {
      MyStack theStack = new MyStack(10); 
      theStack.push(10);
      theStack.push(20);
      theStack.push(30);
      theStack.push(40);
      theStack.push(50);
      while (!theStack.isEmpty()) {
         long value = theStack.pop();
         System.out.print(value);
         System.out.print(" ");
      }
      System.out.println("");
   }
}`

9.Java 实例 – 链表元素查找

import java.util.LinkedList;
 
public class Main {
   public static void main(String[] args) {
      LinkedList lList = new LinkedList();
      lList.add("1");
      lList.add("2");
      lList.add("3");
      lList.add("4");
      lList.add("5");
      lList.add("2");
      System.out.println("元素 2 第一次出现的位置:" + lList.indexOf("2"));
      System.out.println("元素 2 最后一次出现的位置:"+ lList.lastIndexOf("2"));
   }
}

10.Java 实例 – 压栈出栈的方法实现字符串反转

import java.io.IOException;
 
public class StringReverserThroughStack {
   private String input; 
   private String output;
   public StringReverserThroughStack(String in) {
      input = in;
   }
   public String doRev() {
      int stackSize = input.length(); 
      Stack theStack = new Stack(stackSize); 
      for (int i = 0; i < input.length(); i++) {
         char ch = input.charAt(i); 
         theStack.push(ch); 
      }
      output = "";
      while (!theStack.isEmpty()) {
         char ch = theStack.pop(); 
         output = output + ch; 
      }
      return output;
   }
   public static void main(String[] args) 
   throws IOException {
      String input = "www.w3cschool.cc";
      String output;
      StringReverserThroughStack theReverser = 
      new StringReverserThroughStack(input);
      output = theReverser.doRev();
      System.out.println("反转前: " + input);
      System.out.println("反转后: " + output);
   }
   class Stack {
      private int maxSize;
      private char[] stackArray;
      private int top;
      public Stack(int max) {
         maxSize = max;
         stackArray = new char[maxSize];
         top = -1;
      }
      public void push(char j) {
         stackArray[++top] = j;
      }
      public char pop() {
         return stackArray[top--];
      }
      public char peek() {
         return stackArray[top];
      }
      public boolean isEmpty() {
         return (top == -1);
      }
   }
}

11.Java 实例 – 队列(Queue)用法

import java.util.LinkedList;
import java.util.Queue;
 
public class Main {
    public static void main(String[] args) {
        //add()和remove()方法在失败的时候会抛出异常(不推荐)
        Queue<String> queue = new LinkedList<String>();
        //添加元素
        queue.offer("a");
        queue.offer("b");
        queue.offer("c");
        queue.offer("d");
        queue.offer("e");
        for(String q : queue){
            System.out.println(q);
        }
        System.out.println("===");
        System.out.println("poll="+queue.poll()); //返回第一个元素,并在队列中删除
        for(String q : queue){
            System.out.println(q);
        }
        System.out.println("===");
        System.out.println("element="+queue.element()); //返回第一个元素 
        for(String q : queue){
            System.out.println(q);
        }
        System.out.println("===");
        System.out.println("peek="+queue.peek()); //返回第一个元素 
        for(String q : queue){
            System.out.println(q);
        }
    }
}

12.Java 实例 – 获取向量的最大元素

import java.util.Collections;
import java.util.Vector;
 
public class Main {
   public static void main(String[] args) {
      Vector v = new Vector();
      v.add(new Double("3.4324"));
      v.add(new Double("3.3532"));
      v.add(new Double("3.342"));
      v.add(new Double("3.349"));
      v.add(new Double("2.3"));
      Object obj = Collections.max(v);
      System.out.println("最大元素是:"+obj);
   }
}

13.Java 实例 – 链表修改

import java.util.LinkedList;
 
public class Main {
   public static void main(String[] a) {
      LinkedList officers = new LinkedList();
      officers.add("B");
      officers.add("B");
      officers.add("T");
      officers.add("H");
      officers.add("P");
      System.out.println(officers);
      officers.set(2, "M");
      System.out.println(officers);
   }
}

14.Java 实例 – 旋转向量

import java.util.Collections;
import java.util.Vector;
 
public class Main {
   public static void main(String[] args) {
      Vector<String> v = new Vector();
      v.add("1");
      v.add("2");
      v.add("3");
      v.add("4");
      v.add("5");
      System.out.println(v);
      Collections.swap(v, 0, 4);
      System.out.println("旋转后");
      System.out.println(v);
   }
}

原文地址:https://blog.csdn.net/qq_54122113/article/details/142868150

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!