java实验十理论+实践

本文详细介绍了Java中的字节流和字符流的区别,包括字节流处理所有类型数据,字符流处理字符数据,以及在处理文本数据时的优先选择。通过示例代码展示了字节流和字符流的使用,包括FileOutputStream和FileReader的使用,并指出了代码中的错误和修正。此外,还提供了创建和读取文件的实例,以及计算文件字符、单词和行数的方法。
摘要由CSDN通过智能技术生成

本博文源于java课堂上的作业,理论和实践。有需要的读者可以收藏

理论

1、

在这里插入图片描述

2、

在这里插入图片描述

3、

在这里插入图片描述

4、

在这里插入图片描述

5、

在这里插入图片描述

6、

在这里插入图片描述

字节流读取的时候,读到一个字节就返回一个字节; 字符流使用了字节流读到一个或多个字节(中文对应的字节 数是两个,在 UTF-8 码表中是 3 个字节)时。先去查指定的编码表,将查到的字符返回。 字节流可以处理所有类型数 据,如:MP3,AVI 视频文件,图片,而字符流只能处理字符数据。只要是处理纯文本数据,就要优先考虑使用字符 流,除此之外都用字节流。字节流主要是操作 byte 类型数据,以 byte 数组为准,主要操作类就是 OutputStream、 InputStream
字符流处理的单元为 2 个字节的 Unicode 字符,分别操作字符、字符数组或字符串,而字节流处理单元为 1 个字 节,操作字节和字节数组。所以字符流是由 Java 虚拟机将字节转化为 2 个字节的 Unicode 字符为单位的字符而成的, 所以它对多国语言支持性比较好!如果是音频文件、图片、歌曲,就用字节流好点,如果是关系到中文(文本)的,用 字符流好点。在程序中一个字符等于两个字节,java 提供了 Reader、Writer 两个专门操作字符流的类。

8、阅读代码,指出其中的错误并改正

import  java.io.*;
2. public  class  Test  {
3.         public  static  void  main(String[]  args)  {
4.                 File  f  =  new  File("1.txt");
5.                 try  {
6.                         FileOutputStream  out  =  new  FileOutputStream(f);
7.                         byte[]  a  =  "hello  world".getBytes();
8.                         out.write(a);
9.                         System.out.println("  >>>成功输出!");
10.                         out.flush();  
11.                 }  catch  (Exception  e)  {
12.                         System.out.println(e.getMessage());
13.                 }
14.                 try  {
15.                         FileReader  in=new  FileReader(f);  
16.                         byte[]  b  =  new  byte[1024];
17.                         int  len  =  in.read(b);
18.                         System.out.println("  >>>成功读取!");
19.                         int  i=0;
20.                         while(b[i]!=0){
21.                                 System.out.print((char)b[i++]);
22.                         }
23.                 }  catch  (Exception  e)  {
24.                         System.out.println(e.getMessage());
25.                 }
26.         }
27. }

17行read函数参数类型错误

8、阅读代码,指出其中的错误并改正

1. import  java.io.*;
2. public  class  Test  {
3.         public  static  void  main(String[]  args)  {
4.                 File  f  =  new  File("1.txt");
5.                 try  {
6.                         FileOutputStream  out  =  new  FileOutputStream(f);
7.                         byte[]  a  =  "hello  world".getBytes();
8.                         out.write(a);
9.                         System.out.println("  >>>成功输出!");
10. out.close();
11.                           //改为out.close()
12.                 }  catch  (Exception  e)  {
13.                         System.out.println(e.getMessage());
14.                 }
15.                 try  {
16.                         FileInputStream  in=new  FileInputStream  (f);  
17.                           //改为FileInputStream  in=new  FileInputStream(f);
18.                         byte[]  b  =  new  byte[1024];
19.                         int  len  =  in.read(b);
20.                         System.out.println("  >>>成功读取!");
21.                         int  i=0;
22.                         while(b[i]!=0){
23.                                 System.out.print((char)b[i++]);
24.                         }
25.                 }  catch  (Exception  e)  {
26.                         System.out.println(e.getMessage());
27.                 }
28.         }
29. }

没有错误

9、阅读代码片段,将该代码片段运行3次,写出每次运行的输出结果1. import java.io.*;

 import  java.io.*;
2. public  class  test1  {
3.         public  static  void  main(String[]  args){
4.                 try  {
5.                         String  file_name  =  "test.txt";
6.                         File  file  =  new  File(file_name);
7.                         if(file.exists())  {
8.                                 System.out.println(file  +  "  is  existed!");
9.                                 file.delete();
10.                         }
11.                         else  {
12.                                 file.createNewFile();
13.                                 System.out.println(file  +  "  has  been  created  successfully!");
14.                         }
15.                 }
16.                 catch  (IOException  e){
17.                         e.printStackTrace();
18.                 }
19.         }
20. }
}

test.txt has been created successfully!

test.txt is existed!

test.txt has been created successfully!

10、阅读代码片段,写出运行的输出结果

. import  java.io.*;
2. public  class  test2  {
3.         public  static  void  main(String[]  args)  {
4.                 File  file  =  new  File("d:/TextRw.txt");
5.                 try  {
6.                         if  (!file.exists())  {
7.                                 file.createNewFile();
8.                         }
9.                         FileOutputStream  fl  =  new  FileOutputStream(file);
10.                         String  str  =  "Name  :  Jack\n";
11.                         String  str2  =  "Id  :  10086\n";
12.                         fl.write(str.getBytes());
13.                         fl.write(str2.getBytes());
14.                         fl.close();
15.                         System.out.println("写入完成!");
16.                         FileInputStream  fis  =  new  FileInputStream(file);
17.                         System.out.println("Read  from:  "  +  file);
18.                         int  d  =  fis.read();
19.                         while  (d  !=  -1)  {
20.                                 System.out.print((char)  d);
21.                                 d  =  fis.read();
22.                         }
23.                         System.out.println("输出完成!");
24.                         fis.close();
25.                 }  catch  (Exception  e)  {
26.                         e.printStackTrace();
27.                 }
28.         }
29. }

11、请在当前目录下新建一个”test.txt”文件,在第一行写入”Hello World!”,在第二行写入“JAVA程序设计”。写入完成后请将文件中的内容读取,并输出到屏幕上,可以尝试多种方法实现文件的基本读取与写入。

package com.company;


import jdk.jfr.events.FileWriteEvent;
import jdk.nashorn.internal.ir.visitor.NodeOperatorVisitor;

import java.util.*;


import java.io.*;
class Main{
    public static void main(String[] args)  throws IOException {
        BufferedReader buffR = null;
        BufferedWriter buffW = null;
        File fi = new File("test.txt");
        try{
            if(!fi.exists()){
                fi.createNewFile();
            }
            buffW = new BufferedWriter(new FileWriter(fi));
            buffW.write("Hello world\n");
            buffW.write("java程序设计");
            buffW.flush();
            buffR = new BufferedReader(new FileReader(fi));
            String temp = null;
            while ((temp = buffR.readLine()) != null) {
                System.out.println(temp);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }finally {
            buffR.close();
            buffW.close();
        }
    }
}



实验

保存至main.java

1

在这里插入图片描述

package com.company;


import jdk.jfr.events.FileWriteEvent;
import jdk.nashorn.internal.ir.visitor.NodeOperatorVisitor;

import java.util.*;


import java.io.*;
class Main{
    public static void main(String[] args)  throws Exception {
        int lineCnt = 0;
        int wrdCount = 0;
        int charCnt = 0;
        FileReader fR = new FileReader("test.txt");
        BufferedReader bufR = new BufferedReader(fR);
        String tmp = null;
        while((tmp = bufR.readLine())!=null){
            System.out.println(tmp);
            lineCnt++;
            String[] split = tmp.split(" ");
            wrdCount += split.length;
            String replace = tmp.replace(" ","");
            charCnt += replace.length();
        }
        bufR.close();
        System.out.println(charCnt + "characters");
        System.out.println(wrdCount + "words");
        System.out.println(lineCnt + "lines");

    }
}



2、

在这里插入图片描述

package com.company;


import jdk.jfr.events.FileWriteEvent;
import jdk.nashorn.internal.ir.visitor.NodeOperatorVisitor;

import javax.naming.StringRefAddr;
import java.util.*;


import java.io.*;
class Main{
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        String filname = sc.next();
        String target = sc.next();
        String replacement = sc.next();
        StringReplace(filname,target,replacement);
    }
    public static void StringReplace(String filename,String target,String replaced) throws IOException {
        FileReader fR = new FileReader(filename);
        BufferedReader  bR = new BufferedReader(fR);
        String tmp = null;
        String replaceStr = "";
        while((tmp = bR.readLine()) != null){
            String replace = tmp.replace(target,replaced);
            replaceStr += replace+'\n';

        }
        bR.close();
        FileWriter fW = new FileWriter(filename);
        BufferedWriter bW = new BufferedWriter(fW);
        bW.write(replaceStr);
        bW.close();
        System.out.println("success");



    }
}



3、

在这里插入图片描述

package com.company;


import jdk.jfr.events.FileWriteEvent;
import jdk.nashorn.internal.ir.visitor.NodeOperatorVisitor;

import javax.naming.StringRefAddr;
import java.util.*;


import java.io.*;
class Main{
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        String filename = scanner.next();
        String newFilename = scanner.next();
        try {
            BinaryToTxt(filename, newFilename);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static void BinaryToTxt(String filename, String newFilename) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(filename);
        int byteCount = 0;
        String container = "";
        while ((byteCount = fileInputStream.read()) != -1){
            String string = Integer.toHexString(byteCount);
            container += string;
        }
        System.out.println(container);
        fileInputStream.close();
        FileWriter fileWriter = new FileWriter(newFilename);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(container);
        bufferedWriter.flush();
        bufferedWriter.close();
    }

}



实验一 1. 使用记事本和命令行程序编写Java应用程序,打印出所有的水仙花数。 2. 程序设计(开发环境不限): 1) 打印出100以内的素数 2) 求1!+2!+……+20! 3) 课后习题2.6 4) 编写程序,命令行窗口输出希腊字母表。(希腊字母表开始为α,最后一个为ω) 实验二 1、设计一个名为figure的图形软件包(package)。包中包含三角形、矩形、圆三个类。要求:(1)每个类都要构造方法并为成员设置get和set方法;(2)每个类都要有计算周长和面积的成员方法;(3)完成该软件包后的编码后,在另一个包的含有main方法的类中编写代码,分别使用图形软件包中的三个类,生成三个对象,并打印出其周长和面积。 2、编写类Factorial,为其添加两个静态方法(方法名自定义)。其中一个使用递归计算n的阶乘,一个使用非递归计算n的阶乘。构造main方法进行测试。 3、按照要求使用Java进行编码。 1) 设计一个教师类Teacher,属性有编号(no)、姓名(name)、年龄(age)、所属学院(seminary),为这些属性设置相应的get和set方法; 2) 为Teacher类添加方法equals;(当两个教师对象的no相同时返回true) 3) 为Teacher类添加方法toString,通过该方法可以返回“编号为**、姓名为**、年龄为**的**学院老师”形式的字符串。 4) 构造main方法进行测试。 4、设计一个带表头的单链表(链表中的元素属于同一类型对象,但对象的类型可以随意),提供以下操作:(1)insert:在某个位置插入对象;(2)delete:在某个位置删除对象;(3)delete:删除链表中与x相同的元素;(4)size:返回当前链表中对象的个数;(5)isEmpty:判断链表是否为空;(6)traverse:遍历链表,打印出所有的元素;(7)getData:取得某个位置的对象。构造main函数进行测试。 实验三 1、按照要求使用Java进行编码。 1) 编写一个抽象类Shape,其中有抽象方法getArea()和getPerimeter() 2) 在Shape类的基础上派生出Rectangle和Circle类,二者都实现了计算面积的方法getArea()和计算周长的方法getPerimeter(); 3) 构造main函数,生成Rectangle和Circle对象,并用Shape类型的变量调用Rectangle和Circle对象的getArea()和getPerim()方法。 2、以电话为父类,移动电话和固定电话为两个子类,并使移动电话实现接口:可移动。固定电话又有子类:无绳电话。定义接口及各类,明确他们的继承关系。 3、在实验2中所实现的Teacher类的基础上,修改Teacher类的代码,要求:由多个Teacher对象所形成的数组可以使用Arrays.sort方法进行排序(编号由低到高排序)。 实验四 1、在main方法中创建一个含有10个元素的int型数组,进行以下操作:(1)将数组元素按照从小到大的顺序排列;(2)对排好序的数组使用折半查找(使用递归和非递归两种形式分别实现)查找某一个int元素。 2、使用一维数组编码实现一个栈(Stack)类,要求提供以下操作:(1)boolean isEmpty():判断栈当前是否为空;(2)入栈操作void push(obj):把数据元素obj插入堆栈;(3)出栈操作Object pop():出栈,并返回删除的数据元素;(4)Object getTop():取堆栈当前栈顶的数据元素并返回。编写代码测试所形成的Stack类,然后利用Stack类实现以下功能:输入一个正整数,输出该整数所对应的二进制数。 3、按照要求使用Java编码。 1) 以类型int[][]声明一个叫matrix的二维数组变量,将矩阵初始化为一个5个元素的数组。 2) 以下列方式为matrix的内部元素赋值:matrix从零开始循环到其长度值;例如索引为i,在每次迭代中,将matrix[i]指向一个新的整数数组,其长度为i。然后用索引变量j,对数组中的每一个元素进行循环。在每次内部循环中,将matrix[i][j]赋值为(i*j)。 3) 通过循环打印matrix中的所有元素,结果为: <> <0> <0 2> <0 3 6> <0 4 8 12> 4、利用二维数组实现一个矩阵类:Matrix。要求提供以下操作:(1)set(int row, int col, double value):将第row行第col列的元素赋值为value;(2)get(int row,int col):取第row行第col列的元素;(3)width():返回矩阵的列数;(4)height():返回矩阵的行数;(5)Matrix add(Matrix b):返回当前矩阵与矩阵b相加后的结果矩阵;(6)Matrix multiply(Matrix b):返回当前矩阵与矩阵b相乘后的结果矩阵。(7)print():打印出当前矩阵的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值