Java(八)

读取类

Scanner

        Scanner可以获取用户的键盘输入,Scanner是一个基于正则表达式的文本扫描器,可以从文件,输入流,字符串中解析基本类型作为数据源。JDK1.5之后出现。

示例

public static void main(String[] args) throws FileNotFoundException {
        //读取文件
        System.out.println("=======读取文件=======");
        Scanner sFile=new Scanner(new File("文件路径"));
        //一行一行读取
        while(sFile.hasNextLine()){
            System.out.println(sFile.nextLine());
        }
        sFile.close();

        //获取用户从键盘输入结果
        System.out.println("========从键盘输入=========");
        Scanner sIn=new Scanner(System.in);
        while (sIn.hasNextLine()){
            String in=sIn.nextLine();
            //输入为exit就退出
            if (in.equals("exit")){
                break;
            }
            System.out.println(in);
        }
        sIn.close();

        //解析字符串
        System.out.println("=========解析字符串==========");
        String input = "1 fish 2 fish red fish blue fish";
        //表示:空格+fish+空格 为分隔符
        Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
        System.out.println(s.nextInt());
        System.out.println(s.nextInt());
        System.out.println(s.next());
        System.out.println(s.next());
        s.close();
 }
运行结果
在这里插入图片描述


BufferedReader

        在JDK1.5之前,还没有Scanner类,读取键盘输入使用BufferedReader。
        BufferedReader是IO流中的一个字符、包装流,它必须建立在另一个字符流的基础上。但是System.in输入是字节流,因此需要使用转换流InputStreamReader将其包装为字符流。

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(br.readLine());
运行结果
在这里插入图片描述





系统相关

System类

        System类代表当前Java程序运行平台。System这个类的构造器是private修饰的,因此不能创建System对象。System类是个final类,因此这个类也不能被继承。这个类的所有方法都是static,也就是说只有静态方法。

public final class System{
...
/** Don't let anyone instantiate this class */
    private System() {
    }
...
}

        System类提供了代表标准输入、标准输出和错误输出的类属性;还提供了一下用于访问环境变量、系统属性的方法;还提供了加载文件和动态链接库的方法。更多方法可以查看官方文档

// 返回当前系统环境的不可修改字符串映射视图。
System.out.println(System.getenv());
//获取指定环境变量的值
System.out.println(System.getenv("PROCESSOR_LEVEL"));
//确定当前系统属性。
System.out.println(System.getProperties());
//运行垃圾收集器。
System.gc();
运行截图:
在这里插入图片描述



Runtime类

        Runtime类代表Java运行时环境。每个Java程序都有一个与之对应的Runtime实例,应用程序通过该对象与运行时环境相连。

public class Runtime {
   private static Runtime currentRuntime = new Runtime();

  /**
    * Returns the runtime object associated with the current Java application.
    * Most of the methods of class <code>Runtime</code> are instance
    * methods and must be invoked with respect to the current runtime object.
    *
    * @return  the <code>Runtime</code> object associated with the current
    *          Java application.
    */
   public static Runtime getRuntime() {
       return currentRuntime;
   }
   /** Don't let anyone else instantiate this class */
   private Runtime() {}
...
}

        从上面部分源码也可以看出,Runtime的构造器是private的,因此不能创建Runtime类的实例。但是可以通过getRuntime()方法获取。

// 获取实例
Runtime r=Runtime.getRuntime();
//启动记事本
r.exec("notepad.exe");




常用类

Object类

        Object类时所有类、数组、枚举类的父类。也就是说任何类型的对象都可以赋值给Object类型的变量。
在这里插入图片描述

常用方法

  • protected Object clone()
    Creates and returns a copy of this object.
  • boolean equals(Object obj)
    Indicates whether some other object is “equal to” this one.
  • protected void finalize()
    Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
  • Class<?> getClass()
    Returns the runtime class of this Object.
  • int hashCode()
    Returns a hash code value for the object.
  • void notify()
    Wakes up a single thread that is waiting on this object’s monitor.
  • void notifyAll()
    Wakes up all threads that are waiting on this object’s monitor.
  • String toString()
    Returns a string representation of the object.
  • void wait()
    Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
  • void wait(long timeout)
    Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
  • void wait(long timeout, int nanos)
    Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.



String、StringBuffer、StringBuilder

String:String类时不可变类,一旦一个String对象创建后就不能修改,包括字符内容也不能修改,直到这个对象被销毁。

String s1=new String("Hello!");
s1=s1+"Nice to meet you!";
String s1=new String(“Hello!”);
在这里插入图片描述
s1=s1+“Nice to meet you!”;
在这里插入图片描述
StringBuffer:一个字符序列可变的字符串,当一个StringBuffer对象创建以后,通过StringBuffer提供的append、insert、reverse、setChatAt、setLength等方法可以改变这个字符串对象的字符序列。一旦通过StringBuffer生成最终想要的字符串,就可以调用toString方法将其转换为一个String对象。
StringBuilder:JDK1.5之后又新增了一个StringBuilder类,它代表字符串对象。StringBuilder和StringBuffer基本相似,构造器和方法也基本上相同。不同点是, StringBuffer是线程安全的,而 StringBuilder不是线程安全的,所有StringBuilder的性能会高于StringBuffer的性能。

        StringBuffer和StringBuilder都有length和capacity两个属性,其中length代表其包含的字符序列的长度,与String对象的length不同的是,StringBuffer和StringBuilder的长度是可变的,而String是不可变的。StringBuffer和StringBuilder可以通过length()和setLeng(int len)方法访问长度和修改长度。capacity属性代表的是容量,capacity通常比length大,一般程序无需关系capacity属性。



Math类

        从上面的源码中可以看出,Math类被final修饰,意味着这个类不能被继承,构造器是私有的,这个类无法创建实例。Math的所有方法和变量都是静态的,里面有两个静态常量EPI,也就是常量e和π。

public final class Math {

    /**
     * Don't let anyone instantiate this class.
     */
    private Math() {}
/**
     * The {@code double} value that is closer than any other to
     * <i>e</i>, the base of the natural logarithms.
     */
    public static final double E = 2.7182818284590452354;

    /**
     * The {@code double} value that is closer than any other to
     * <i>pi</i>, the ratio of the circumference of a circle to its
     * diameter.
     */
    public static final double PI = 3.14159265358979323846;

...
}

更多方法查看官方文档

Math里面有个random()方法,用于生成随机数,生成随机数范围是大于等于0且小于1

//生成的随机数r范围:0≤r<1
double r=Math.random();



Random类

        Random类专门用于生成一个伪随机数,它有两个构造器:一个默认无参,会有一个默认的种子;一个需要程序员显示传入一个long类型的参数作为种子。

public
class Random implements java.io.Serializable {

    private final AtomicLong seed;

    public Random() {
        this(seedUniquifier() ^ System.nanoTime());
    }

    public Random(long seed) {
        if (getClass() == Random.class)
            this.seed = new AtomicLong(initialScramble(seed));
        else {
            // subclass might have overriden setSeed
            this.seed = new AtomicLong();
            setSeed(seed);
        }
    }

}

在这里插入图片描述

//无种子
System.out.println("======无种子=====");
Random random=new Random();
System.out.println(random.nextDouble());
System.out.println(random.nextDouble());
System.out.println(random.nextInt());

//带种子
System.out.println("======带种子=====");
Random r2=new Random(10);
System.out.println(r2.nextDouble());
System.out.println(r2.nextDouble());
System.out.println(r2.nextBoolean());
运行结果
在这里插入图片描述
在这里插入图片描述

        当两个Random对象种子相同时,会产出相同的数字序列。也就是说,Random对象产生的数字不是真正的随机的,而是一种伪随机。



BigDecimal类

        我们知道在很多语言中,float和double两种基本类型的浮点数容易引起精度丢失,尤其是在算术运算时更容易发生。为更准确计算浮点数,Java提供了BigDecimal类,该类有大量构造器。

public class BigDecimal extends Number implements Comparable<BigDecimal> {

}

        如果必须使用double浮点数作为BigDecimal构造器的参数时,不要直接将该double浮点数作为构造器参数,而是应该通过BigDecimal.valueOf(double value)静态方法来创建BigDecimal对象。

注意:不要直接使用double浮点数来创建一个DigDecimal对象,否则同样会发生精度丢失问题。

BigDecimal还提供了加减乘除操作的方法:
在这里插入图片描述

BigDecimal的实现利用了BigInteger,BigDecimal用的比BigInteger多。




处理日期的类

Date类

         Date类提供了6个构造器,但是有4个已经Deprecate(java不推荐使用)了。使用不推荐的方法时,编译器会发出警告,并导致程序性能、安全等方面的问题。

public class Date
剩余两个支持使用的构造器
Date():生成一个当前日期时间的Date对象。
Date(long date):根据指定的long整型生成一个Date对象。便是创建的Date对象离 GMT 1970年1月1日00:00:00之前的时差,单位 毫秒

Calendar类

        因为Date类设计上的缺陷,Java提供了一个Calendar类更好处理时间。Calendar类是个抽象类,用于表示日历。

public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> {
...
 	public static Calendar getInstance(){
        return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
    }

...
}

        GregorianCalendar类时Calendar类的一个子类。

        Calendar类是一个抽象类,因此它的构造器不能用于创建对象,但是他提供了几个静态方法getInstance方法类获取Calendar对象。
        Calendar与Date类都是日期的工具类,它们之间可以自由转换。

Calendar calendar=Calendar.getInstance();
//Calendar==>date
Date date=calendar.getTime();

Calendar calendar2=Calendar.getInstance();
//Date==>Calendar
calendar2.setTime(date);

TimeZone类

        在地里上,地球被划分为24个时区,北京时间属性东八区,程序中默认实现是以格林威治时间为标准的,这样就产生了8个小时的时间差,为使程序通用,可以使用TimeZone设置程序中时间所属时区,其中TimeZone代表时区。
        TimeZone是一个抽象类。但是可以通过getDefault()和getTimeZone()方法来获取这个类的实例。

abstract public class TimeZone implements Serializable, Cloneable {
 	public TimeZone() {
 	}
  	public static TimeZone getDefault() {
        return (TimeZone) 			getDefaultRef().clone();
  }
  	public static synchronized TimeZone getTimeZone(String ID) {
        return getTimeZone(ID, true);
	}
...
}




正则表达式

        正则表达式是一个用于匹配字符串的模板。
        String类的一些方法(例如matches()replace()replceFirst()split()等方法)都依赖Java提供的正则表达式。除此之外,Java还提供了两个类Pattern和Matcher专门用于提供正则表达式支持。

作用

  1. 测试字符串内的模式。
    例如,可以测试输入字符串,以查看字符串内是否出现电话号码模式或信用卡号码模式。这称为数据验证。
  2. 替换文本。
    可以使用正则表达式来识别文档中的特定文本,完全删除该文本或者用其他文本替换它。
  3. 基于模式匹配从字符串中提取子字符串。

java正则表达式,java.util.regex包主要包括三个类:

  1. Pattern 类
    pattern 对象是一个正则表达式的编译表示。Pattern 类没有公共构造方法。要创建一个 Pattern 对象,你必须首先调用其公共静态编译方法,它返回一个 Pattern 对象。该方法接受一个正则表达式作为它的第一个参数。
  2. Matcher 类
    Matcher 对象是对输入字符串进行解释和匹配操作的引擎。与Pattern 类一样,Matcher 也没有公共构造方法。你需要调用 Pattern 对象的 matcher 方法来获得一个 Matcher 对象。
  3. PatternSyntaxException
    PatternSyntaxException 是一个非强制异常类,它表示一个正则表达式模式中的语法错误。
import java.util.regex.*;
 
class RegexExample1{
   public static void main(String args[]){
      String content = "I am noob " +
        "from runoob.com.";
 
      String pattern = ".*runoob.*";
 
      boolean isMatch = Pattern.matches(pattern, content);
      System.out.println("字符串中是否包含了 'runoob' 子字符串? " + isMatch);
   }
}

注意:在其他的语言中(如Perl),一个反斜杠 \ 就足以具有转义的作用,而在 Java 中正则表达式中则需要有两个反斜杠\\才能被解析为其他语言中的转义作用。因此,表示一个普通的反斜杠是 \\\\




程序国际化

        国际化是指应用程序运行时,可根据客户端请求来着的国家、地区、语言的不同而显示不同的界面。
        国际化的英文单词是Internationlization,但因为这个单词太长,简写为I18N,I表示第一个字母,18表示中间省略18个字母,N表示单词的最后一个字母。

国家化思路

        Java国际化的思路是将程序的标签、提示信息放在资源文件中,程序中支持哪些国家语言,就提供对应的资源文件。资源文件是key-value对,每个资源文件的key是不变的,但value随国家语言变化。

国际化的三个类

  1. java.util.ResourceBundle:用于加载一个国家、语言资源包。
  2. java.util.Locale:用于封装一个特定的国家区域、语言环境。
  3. java.text.MessageFormat:用于格式化带占位符的字符串。



资源文件的命名

  1. badeName_language_country.properties
  2. baseName_language.properties
  3. baseName.properties

        baseName是资源文件的基本名,用户可以自定义。language和country是不可以随意变的,必须是Java支持的语言和国家。

Java支持的语言国家

public static void main(String[] args) {
    //返回Java所支持的全部国家和语言数组
      Locale[] localeList=Locale.getAvailableLocales();
      for (Locale locale:localeList){
          //打印出所有支持的国家和语言
          System.out.println(locale.getDisplayCountry()+" = "+locale.getCountry()+"  ;  "+locale.getDisplayLanguage()+" = "+locale.getLanguage());
      }

}
运行部分截图
在这里插入图片描述

国际化配置

文件目录
文件目录

Greet.java

public class Greet {

    public static void main(String[] args) {
        //取得系统默认国家语言环境
        Locale myLocale=Locale.getDefault();
        //根据指定国家语言环境加载资源文件
        ResourceBundle bundle=ResourceBundle.getBundle("greet",myLocale);
        //打印从文件中获取的信息
        System.out.println(bundle.getString("hello"));
    }
}

greet_en_US.properties

# 资源文件内容是key-value
hello = Welcome you!

greet_zh_CN.properties

# 资源文件内容key-value
hello = 您好!
运行结果
在这里插入图片描述

格式化类

        Format是个抽象类,Format抽象类三个子类子类:MessageFormatNumberFormatDateFormat,分别对字符串、数值和日期进行格式化。

MessageFormat

public static void main(String[] args) {
     //取得系统默认国家语言环境
     Locale myLocale=Locale.getDefault();
     //根据指定国家语言环境加载资源文件
     ResourceBundle bundle=ResourceBundle.getBundle("greet",myLocale);
     //获取配置文件的today信息
     String today=bundle.getString("today");
     //使用MessageFormat为带占位符的字符串传入参数
     System.out.println(MessageFormat.format(today,"Archer",new Date()));

}

greet_en_US.properties

# 资源文件内容是key-value
hello = Welcome you!
today = Hi ,{0} ,today is {1}

greet_zh_CN.properties

# 资源文件内容key-value
hello = 您好!
today=msg=您好呀,{0},今天是{1}
运行结果:
在这里插入图片描述
NumberFormat Format方法
parse方法
DateFormat format方法
parse方法
Number
String
Date
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值