java入门-数组,日期和流

一、数组

 

数组是用来存储固定大小的同类型元素

1、定义

语法

dataType[] arrayRefVar;   // 首选的方法
 
或
 
dataType arrayRefVar[];  // 效果相同,但不是首选方法

arrayRefVar = new dataType[arraySize];

示例:

    /**
	 * 数组测试
	 */
	@Test
	public void arrTest(){
		int arr[] = {2,4,6,8};	//定义整型数组
		int[] arr2 = {1,3,5,7};
		
		String[] ssArr = {"aa","bb","cc"};	//定义字符串数组
		
		double[] ddArr = new double[5];	//定义double数组
		for(int i=0;i<5;i++){
			ddArr[i] = i;
		}
		
		for(int a : arr){//数组循环
			System.out.print(a+" ");
		}
		System.out.println();
		for(int i=0;i<ssArr.length;i++){//数组循环
			System.out.print(ssArr[i]+" ");
		}
		System.out.println();
		double max = ddArr[0];
		for(int i=1;i<ddArr.length;i++){//循环查找最大值
			if(ddArr[i] > max){
				max = ddArr[i];
			}
		}
		System.out.print("ddArr中的最大值是: "+max);
	}

结果:

2 4 6 8 
aa bb cc 
ddArr中的最大值是: 4.0

 2、多维数组

示例:

    /**
	 * 多维数组
	 */
	@Test
	public void arrMutilTest(){
		int arr[][] = new int[2][];	//定义整型数组
		int a1[] = {1,3,5,7,9};
		int a2[] = {2,4,6,8,10};
		
		arr[0] = a1;
		arr[1] = a2;
		arr[0][4] = 11;
		arr[1][4] = 12;
		
		for(int i=0;i<2;i++){
			for(int j=0;j<5;j++){
				System.out.println("arr第"+i+"行,第"+j+"列:"+arr[i][j]);
			}
		}
	}

结果:

arr第0行,第0列:1
arr第0行,第1列:3
arr第0行,第2列:5
arr第0行,第3列:7
arr第0行,第4列:11
arr第1行,第0列:2
arr第1行,第1列:4
arr第1行,第2列:6
arr第1行,第3列:8
arr第1行,第4列:12

3、Arrays 类 

1、通过 fill 方法,给数组赋值

2、sort排序-升序

3、通过 equals 方法比较数组中元素值是否相等

4、通过 binarySearch 方法能对排序好的数组进行二分查找法操作

示例:

/**
	 * 多维数组
	 */
	@Test
	public void arrayTest(){
		int a1[] = {1,5,3,9,6,18,15,17};
		int a2[] = {1,5,3,9,6,18,15,17};
		int a3[] = {1,5,3,9,6,18,15,17};
		Arrays.sort(a1);
		Arrays.sort(a2);
		Arrays.sort(a3);
		for(int a : a1){
			System.out.print(a+" ");
		}
		System.out.println();
		
		Arrays.fill(a1, 30);
		for(int a : a1){
			System.out.print(a+" ");
		}
		System.out.println();
		
		System.out.println(Arrays.binarySearch(a2, 15));
		
		System.out.println(Arrays.equals(a2, a3));
	}

结果:

1 3 5 6 9 15 17 18 
30 30 30 30 30 30 30 30 
5
true

二、日期时间 

java.util 包提供了 Date 类来封装当前的日期和时间

1、定义

    @Test
	public void dateTest(){
		Date now = new Date();	//定义当前时间
		Long millisec = now.getTime();	//获取时间毫秒数 1970年1月1日起的毫秒数
		
		Date d1 = new Date(millisec);	//根据毫秒数定义日期
	}

2、日期比较

1)使用 getTime() 方法获取两个日期(自1970年1月1日经历的毫秒数值),然后比较这两个值

2)使用方法 before(),after() 和 equals()。例如,一个月的12号比18号早,则 new Date(99, 2, 12).before(new Date (99, 2, 18)) 返回true。

3)使用 compareTo() 方法,它是由 Comparable 接口定义的,Date 类实现了这个接口

3、日期格式化

SimpleDateFormat

示例:

    @Test
	public void compareDate() throws Exception{
	    SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
	    Date d1 = ft.parse("2021-07-29 23:59:59");
		Date d2 = ft.parse("2021-07-30 23:59:59");
	    System.out.println("格式化后时间为d1:" +         ft.format(d1)+",d2:"+ft.format(d2)+","+d1.before(d2));
	}

结果:

格式化后时间为d1:2021-07-29 11:59:59,d2:2021-07-30 11:59:59,true

4、Calendar类 

我们现在已经能够格式化并创建一个日期对象了,但是我们如何才能设置和获取日期数据的特定部分呢,比如说小时,日,或者分钟? 我们又如何在日期的这些部分加上或者减去值呢? 答案是使用Calendar 类。

Calendar类是一个抽象类,在实际使用时实现特定的子类的对象,创建对象的过程对程序员来说是透明的,只需要使用getInstance方法创建即可。

示例:

    @Test
	public void calTest() throws Exception{
		SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
		
		Calendar c = Calendar.getInstance();
		c.set(2021, 06, 31, 17, 16, 23);	//设置时间
		Date d1 = c.getTime();
		System.out.println("d1:" + ft.format(d1));
		/**
		 * 	Calendar.ERA:表示无加减;
			Calendar.YEAR:年
			Calendar.MONTH:月 月份从0开始的,所以真实月份需要加1
			Calendar.DATE:日
			Calendar.HOUR:小时
			Calendar.MINUTE:分钟
			Calendar.SECOND:秒
		 */
		c.add(Calendar.DATE, 1);//增加1天 ,负数为减1天 
		Date d2 = c.getTime();
		System.out.println("d2:" + ft.format(d2));
		
	}

结果:

d1:2021-07-31 05:16:23
d2:2021-08-01 05:16:23

Calendar.DAY_OF_WEEK :1代表星期日、2代表星期1、3代表星期二,以此类推

5、GregorianCalendar类

Calendar类实现了公历日历,GregorianCalendar是Calendar类的一个具体实现。

    @Test
	public void glDateTest(){
		String months[] = {
	      "Jan", "Feb", "Mar", "Apr",
	      "May", "Jun", "Jul", "Aug",
	      "Sep", "Oct", "Nov", "Dec"};
	      
	      int year;
	      // 初始化 Gregorian 日历
	      // 使用当前时间和日期
	      // 默认为本地时间和时区
	      GregorianCalendar gcalendar = new GregorianCalendar();
	      // 显示当前时间和日期的信息
	      System.out.print("Date: ");
	      System.out.print(months[gcalendar.get(Calendar.MONTH)]);
	      System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
	      System.out.println(year = gcalendar.get(Calendar.YEAR));
	      System.out.print("Time: ");
	      System.out.print(gcalendar.get(Calendar.HOUR) + ":");
	      System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
	      System.out.println(gcalendar.get(Calendar.SECOND));
	      
	      // 测试当前年份是否为闰年
	      if(gcalendar.isLeapYear(year)) {
	         System.out.println("当前年份是闰年");
	      }
	      else {
	         System.out.println("当前年份不是闰年");
	      }
	}

结果:

Date: Jul 31 2021
Time: 5:27:44
当前年份不是闰年

6、计算相差天数 

    @Test
	public void getDiffDays() {
		try {
			SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
			Date d1 = ft.parse("2021-07-12 21:32:43");
			Date d2 = ft.parse("2021-07-30 23:59:59");
			
			Long l1 = d1.getTime();
			Long l2 = d2.getTime();
			Long diffMill = l2 - l1;
			
			Long diffDays = diffMill/(60*60*24*1000);
			
			 System.out.println("格式化后时间为d1:" + ft.format(d1)+",d2:"+ft.format(d2)+",相差天数:"+diffDays);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

结果:

格式化后时间为d1:2021-07-12 09:32:43,d2:2021-07-30 11:59:59,相差天数:18

7、jdk1.8操作日期

 

    @Test
	public void jdk8Date() {
		try {
			SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
			Date d1 = ft.parse("2021-07-12 21:32:43");
			Date d2 = ft.parse("2021-07-30 23:59:59");
			
			Instant instant = d1.toInstant();
		    ZoneId zone = ZoneId.systemDefault();
		    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
		    LocalDateTime ld1 = localDateTime.plusDays(1);	//减一天,LocalDateTime操作日期十分方便
		    
		    instant = ld1.atZone(zone).toInstant();
		    Date d3 = Date.from(instant);
			
			 System.out.println("格式化后时间为d1:" + ft.format(d1)+",d2:"+ft.format(d2)+",d3:"+ ft.format(d3));
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

格式化后时间为d1:2021-07-12 09:32:43,d2:2021-07-30 11:59:59,d3:2021-07-13 09:32:43 

 三、java流

1、字节流读

//字节流读取文件
	public static void readFileByte(){
		try {
			File file = new File("E:\\test.txt");
			//创建写入流  注意:如果不存在会自动创建,如果存在,里面的内容会被覆盖
			FileInputStream fis = new FileInputStream(file);
			
			/*byte[] by= new byte[(int) (file.length())];  
            fis.read(by);  
            String str = new String(by);  
            System.out.println(str); 
            fis.close(); */
			
			// 将文件输入流打包成缓冲输入流  
            BufferedInputStream bis = new BufferedInputStream(fis);  
  
            int len = bis.available();// 得到流中的字节数  
            // 方式一:通过流的长度决定读的次数  
            // while(len>0){  
            // //读取流中的一个字节  
            // int b = fis.read();  
            // System.out.println("字节:"+b);  
            // len = fis.available();  
            // }  
  
            byte[] bs = new byte[len];  
  
            // 方式二,通过读取的字节判断读取的次数〉若为-1,就结束  
            // int i=0;  
            // int b = fis.read();  
            // while(b!=-1){  
            // System.out.println("字节:"+b);  
            // //将字节保存到字节数组  
            // bs[i]=(byte)b;  
            // i++;  
            //  
            // b = fis.read();  
            // }  
  
            // 方式三:直接将数据读取到字节数组,数组有多大,就读取多少次  
            bis.read(bs);  
            fis.close();  
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

2、字节流写

public static void writeFileByte(){
		File file = new File("E:\\test.txt");
		File file2 = new File("E:\\test2.txt");
		 //创建输出流 
	    try {
	    	 //读  
            FileInputStream fis = new FileInputStream(file); 
			
			byte[]  b = new byte[(int) file.length()];
			 //创建输入缓冲流  
            BufferedInputStream bis = new BufferedInputStream(fis);  
            bis.read(b);
            fis.close();
            
            //创建输出缓冲流  
            FileOutputStream fos=new FileOutputStream(file2,true);
            BufferedOutputStream bos = new BufferedOutputStream(fos);  
            //直接写保存在数组中的数据  
            bos.write(b);  
            //强制写出来  
            bos.flush();  
            //关闭流空间  
            fos.close();  
            
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}

3、字符流读取文件

第二种方式可以实现字节流转字符流

public static void readFile(){
		
		//方式一、FileReader
		File file = new File("E:\\test.txt");
		FileReader filereader;
		try {
			filereader = new FileReader(file);
		
			BufferedReader bf =new BufferedReader(filereader);
			String read;
			while((read=bf.readLine())!=null){
			    System.out.println(read);
			}
			filereader.close();
			bf.close();
			
			//方式二 InputStreamReader
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr =new InputStreamReader(fis);
			BufferedReader br =new BufferedReader(isr);
			String read2;
			while((read2=br.readLine())!=null){
			    System.out.println(read2);
			}
			fis.close();
			isr.close();
			br.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

4、字符流写入文件


    public static void writeFile(){
		try{
			 String data = "This content will append to the end of the file";            
			 File file = new File("E:\\test3.txt");
	         //如果文件不存在则创建
	         if(!file.exists()){
	          file.createNewFile();
	         }
	         //true 表示可以将数据写入文件的末尾而不会替换文件原来的内容
	         FileWriter fileWritter = new FileWriter(file,true);
	         BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
	         bufferWritter.write(data);
	         bufferWritter.close();
 
	         System.out.println("写入成功");
        }catch(Exception e){
        	e.printStackTrace();
        }
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wwwzhouzy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值