java怎样通过io流获取一个类

java怎样通过io流获取一个类,第1张

Java中的 IO流文件有读取,写入,复制

//构造文件File类

File f=new File(fileName);

//判断是否为目录

fisDirectory();

//获取目录下的文件名

String[] fileName=flist();

//获取目录下的文件

File[] files=flistFiles();

Java读取文件代码:

package comyybfile;  

  

import javaioFile;  

import javaioFileInputStream;  

import javaioInputStream;  

  

  读取文件: 

  1、找到指定的文件 

  2、根据文件创建文件的输入流 

  3、创建字节数组 

  4、读取内容,放到字节数组里面 

  5、关闭输入流 

 /  

public class FileRead {  

  

    public static void main(String[] args) {  

        // 构建指定文件  

        File file = new File("E:" + Fileseparator + "hellotxt");  

        InputStream in = null;  

        try {  

            // 根据文件创建文件的输入流  

            in = new FileInputStream(file);  

            // 创建字节数组  

            byte[] data = new byte[1024];  

            // 读取内容,放到字节数组里面  

            inread(data);  

            Systemoutprintln(new String(data));  

        } catch (Exception e) {  

            eprintStackTrace();  

        } finally {  

            try {  

                // 关闭输入流  

                inclose();  

            } catch (Exception e) {  

                eprintStackTrace();  

            }  

        }  

    }  

  

}

Java文件写入代码:

package comyybfile;  

  

import javaioFile;  

import javaioFileOutputStream;  

import javaioOutputStream;  

  

  写入文件: 

  1、找到指定的文件 

  2、根据文件创建文件的输出流 

  3、把内容转换成字节数组 

  4、向文件写入内容 

  5、关闭输入流 

 /  

public class FileWriter {  

  

    public static void main(String[] args) {  

        // 构建指定文件  

        File file = new File("E:" + Fileseparator + "hellotxt");  

        OutputStream out = null;  

        try {  

            // 根据文件创建文件的输出流  

            out = new FileOutputStream(file);  

            String message = "我是好人。";  

            // 把内容转换成字节数组  

            byte[] data = messagegetBytes();  

            // 向文件写入内容  

            outwrite(data);  

        } catch (Exception e) {  

            eprintStackTrace();  

        } finally {  

            try {  

                // 关闭输出流  

                outclose();  

            } catch (Exception e) {  

                eprintStackTrace();  

            }  

        }  

    }  

  

}

Java复制文件代码:

<span style="font-size:18px;">package comyybfile;  

  

import javaioFile;  

import javaioFileInputStream;  

import javaioFileOutputStream;  

import javaioInputStream;  

import javaioOutputStream;  

  实现思路: 

  1、构建源文件与目标文件 

  2、源文件创建输入流,目标文件创建输出流 

  3、创建字节数组 

  4、使用循环,源文件读取一部分内容,目标文件写入一部分内容,直到写完所有内容 

  5、关闭源文件输入流,目标文件输出流 

 /  

public class FileCopy {  

  

    public static void main(String[] args) {  

        // 构建源文件  

        File file = new File("E:" + Fileseparator + "HelloWorldtxt");  

        // 构建目标文件  

        File fileCopy = new File("D:" + Fileseparator + "HelloWorld");  

        InputStream in = null;  

        OutputStream out = null;  

        try {  

            // 目标文件不存在就创建  

            if (!(fileCopyexists())) {  

                fileCopycreateNewFile();  

            }  

            // 源文件创建输入流  

            in = new FileInputStream(file);  

            // 目标文件创建输出流  

            out = new FileOutputStream(fileCopy, true);  

            // 创建字节数组  

            byte[] temp = new byte[1024];  

            int length = 0;  

            // 源文件读取一部分内容  

            while ((length = inread(temp)) != -1) {  

                // 目标文件写入一部分内容  

                outwrite(temp, 0, length);  

            }  

        } catch (Exception e) {  

            eprintStackTrace();  

        } finally {  

            try {  

                // 关闭文件输入输出流  

                inclose();  

                outclose();  

            } catch (Exception e) {  

                eprintStackTrace();  

            }  

        }  

    }  

  

}</span><span style="font-size: 24px;">  

</span>

java中可以使用file对象,获取当前电脑硬盘基本信息,示例如下:

import javaioFile;

 

public class DiskSpaceDetail {

 

    public static void main(String[] args) {

 

        File diskPartition = new File("C:");

 

        long totalCapacity = diskPartitiongetTotalSpace(); 

 

        long freePartitionSpace = diskPartitiongetFreeSpace(); 

        long usablePatitionSpace = diskPartitiongetUsableSpace(); 

 

        Systemoutprintln(" Sizes in Mega Bytes \n");

 

        Systemoutprintln("Total C partition size : " + totalCapacity / (10241024) + " MB");

        Systemoutprintln("Usable Space : " + usablePatitionSpace / (1024 1024) + " MB");

        Systemoutprintln("Free Space : " + freePartitionSpace / (1024 1024) + " MB");

 

        Systemoutprintln("\n Sizes in Giga Bytes \n");

 

        Systemoutprintln("Total C partition size : " + totalCapacity / (102410241024) + " GB");

        Systemoutprintln("Usable Space : " + usablePatitionSpace / (1024 10241024) + " GB");

        Systemoutprintln("Free Space : " + freePartitionSpace / (1024 10241024) + " GB");

    }

}

对于远程监控Linux主机系统CPU,内存使用情况,以前也使用了top等命令,但是最后还是觉得使用vmstat比较好

运行top命令获得系统CPU使用情况有两个缺点,

第一运行top命令,执行的shell语句相对复杂

用top命令获得CPU使用情况的shell语句

top -b -n 2 | grep Cpu |sed 1d | awk '{print $5}' | cut -f 1 -d ""

第二:有时候系统峰值时间很短暂,容易造成误判

注意:运行本例子,你还需要下载第三方ganymed-ssh2-build251beta1jar,改软件主要用于通过ssh远程登录被监控主机

ITjob上。看。的

首先你要明白,try catch和finally的关系,

如果 fileReader = new FileReader异常,catch里面会抛出IOException,但是此时finally里面的代码还是会执行。

所以如果你fileReader = new FileReader异常,导致没有这个对象,那么finally里面

fileReaderclose();

会导致不存在的文件流关闭,所以事先判断,避免出现这个错误。

我这里有一个简单的学生管理系统,你只需要把Student学生类修改成名片类就可以了。你需要新建立一个java文件名为HW4java,复制粘贴以下代码,编译运行就可以了。

import javaioFile;

import javaioFileInputStream;

import javaioFileNotFoundException;

import javaioFileOutputStream;

import javaioIOException;

import javaioObjectInputStream;

import javaioObjectOutputStream;

import javaioSerializable;

import javautilArrays;

import javautilComparator;

import javautilScanner;

class Student implements Comparable<Student>, Serializable{

    /

  Serializable UID: ensures serialize/de-serialize process will be successful

 /

private static final long serialVersionUID = -3515442620523776933L;

public int getNumber() {

return number;

}

public void setNumber(int number) {

thisnumber = number;

}

public int getAge() {

return age;

}

public void setAge(int age) {

thisage = age;

}

public double getWeight() {

return weight;

}

public void setWeight(double weight) {

thisweight = weight;

}

public String getName() {

return name;

}

public void setName(String name) {

thisname = name;

}

private int number;

    private int age;

    private double weight;

    private String name;

    

    public Student(int number, int age, double weight, String name) {

        thisnumber = number;

        thisage = age;

        thisweight = weight;

        thisname = name;

    }

@Override

public int compareTo(Student o) {

if (thisage == oage) {

return (int)(thisweight - oweight);

}

return thisage - oage;

}

}

class StudentSortByAge implements Comparator<Student> {

@Override

public int compare(Student o1, Student o2) {

return o1getAge() - o2getAge();

}

}

class StudentSortByWeight implements Comparator<Student> {

@Override

public int compare(Student o1, Student o2) {

return (int)(o1getWeight() - o2getWeight());

}

}

public class HW4 {

//passing one and only one instance of scanner instance reduce complexity of program

    public static void main(String[] args) {

        Systemoutprintln("\nWelcome to the System, Choose options below: ");

     printPrompt();

    

     Student[] students = null;

        Scanner scanner = new Scanner(Systemin);

        while(scannerhasNextInt()) {

            switch (scannernextInt()) {

                case 1:

                 Systemoutprintln("Print Student Information");

                 if (students == null) {

                 Systemoutprintln("Please Initilise N students first");

                 } else {

                 printStudents(students);

                 }

                 printPrompt();

                    break;

                case 2:

                    Systemoutprintln("Enter numebr of students you want to create: ");

                    int number = scannernextInt();

                    students = initilise(number, scanner);

                    printPrompt();

                    break;

                case 3:

                 Systemoutprintln("Add a new student");

                 printPrompt();

                 if (students == null) {

                 Systemoutprintln("Please Initilise N students first");

                 } else {

                 int newLength = studentslength + 1;

                 students = ArrayscopyOf(students, newLength);

                 students[newLength - 1] = createStudent(scanner);

                 Systemoutprintln("New student has been added");

                 printPrompt();

                 }

                    break;

                case 4:

                 Systemoutprintln("Sorting by Age, Weight in Asce order");

                 if (students == null) {

                 Systemoutprintln("Please Initilise N students first");

                 } else {

                 Student[] sortedStudents = students;

                 Arrayssort(sortedStudents);

                 printStudents(sortedStudents);

                 }

                 break;

                case 5:

                 Systemoutprintln("Calcaulte Min, Max, Ave of Age and Weight");

                 if (students == null) {

                 Systemoutprintln("Please Initilise N students first");

                 } else {

                 Student[] sortedAgeStudents = students;

                 Arrayssort(sortedAgeStudents,  new StudentSortByAge());

                 Student[] sortedWeightStudents = students;

                 Arrayssort(sortedWeightStudents,  new StudentSortByWeight());

                 int averageAge = 0;

                 double averageWeight = 00;

                 for (Student student : sortedAgeStudents) {

                 averageAge += studentgetAge();

                 averageWeight += studentgetWeight();

                 }

                 averageAge = averageAge / sortedAgeStudentslength;

                 averageWeight = averageWeight / sortedWeightStudentslength;

                 Systemoutprintf("Min Age: %d, Max Age: %d, Ave Age: %d\n", sortedAgeStudents[0]getAge(), sortedAgeStudents[sortedAgeStudentslength - 1]getAge(), averageAge);

                 Systemoutprintf("Min Weight: %f, Max Weight: %f, Ave Weight: %f\n", sortedWeightStudents[0]getWeight(), sortedWeightStudents[sortedWeightStudentslength - 1]getWeight(), averageWeight);

                 }

                 break;

                case 6:

                 Systemoutprintln("Write Student data into file");

                 try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("studentsData"), true))) {

                     ooswriteObject(students);

                     printPrompt();

                 } catch (FileNotFoundException e) {

// TODO Auto-generated catch block

eprintStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

eprintStackTrace();

}

                 break;

                case 7:

                 Systemoutprintln("Read studentData from file");

                 try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("studentsData")))) {

                 students = (Student[]) (oisreadObject());

                 printPrompt();

                 } catch (FileNotFoundException e) {

// TODO Auto-generated catch block

eprintStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

eprintStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

eprintStackTrace();

}

                 break;

                default:

                 scannerclose();

                 Systemoutprintln("Quit");

                    break;

            }

        }

    }

    public static void printPrompt() {

        Systemoutprintln("1: Display current students");

        Systemoutprintln("2: Initilise N students");

        Systemoutprintln("3: Add new student");

        Systemoutprintln("4: Sorting by Age, Weight in Asce order");

        Systemoutprintln("5: Calcaulte Min, Max, Ave of Age and Weight");

        Systemoutprintln("6: Write Student data into file");

        Systemoutprintln("7: Read studentData from file");

    }

    

    public static Student[] initilise(int n, Scanner scanner) {

        Student[] students = new Student[n];

        for (int i = 0; i < n; i ++) {

            students[i] = createStudent(scanner);

        }

        Systemoutprintln("Initilisation of students complete");

        return students;

    }

    public static void printStudents(Student[] students) {

     for (Student student : students) {

     Systemoutprintf("Student: %s, Number: %d, Age: %d, Weight: %f\n", studentgetName(), studentgetNumber(), studentgetAge(), studentgetWeight());

     }

    }

    public static void printSortedStudents(Student[] students) {

     for (Student student : students) {

     Systemoutprintf("Age: %d, Weight: %f, Student: %s, Number: %d\n", studentgetAge(), studentgetWeight(), studentgetName(), studentgetNumber());

     }

    }

    public static Student createStudent(Scanner scanner) {

        int studentNumber = 0, studentAge = 0;

        double studentWeight = 00;

        String studentName = null;

        Systemoutprintln("Enter Student Number: ");

        while(scannerhasNext()) {

            studentNumber = scannernextInt();

            

            Systemoutprintln("Enter Student Age: ");

            studentAge = scannernextInt();

            

            Systemoutprintln("Enter Student Weight: ");

            //nextDouble仅仅读取double的值,在double值后的'\n'将会被nextLine()所读取,所以读取studentName时需要再读取一次nextLine()

            studentWeight = scannernextDouble();

            

            Systemoutprintln("Enter Student Name: ");

            scannernextLine();

            studentName = scannernextLine();

            break;

        }

        return new Student(studentNumber, studentAge, studentWeight, studentName);

    }

}

String line;

while((line=inreadLine)!=null){

Systemoutprint(line);//你可以把他存到数组里或者用输出流输出出去

}

以上就是关于java怎样通过io流获取一个类全部的内容,包括:java怎样通过io流获取一个类、Java如何获得硬盘剩余空间、如何用java实现远程监控linux服务器磁盘io等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/9601039.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-30
下一篇2023-04-30

发表评论

登录后才能评论

评论列表(0条)

    保存