【JAVA学习笔记】66

编程入门 行业动态 更新时间:2024-10-22 20:24:39

【JAVA<a href=https://www.elefans.com/category/jswz/34/1770117.html style=学习笔记】66"/>

【JAVA学习笔记】66

项目代码

1.使用File类和FileWriter类

(1)在判断e盘下是否有文件夹mytemp,如果没有就创建mytemp

public class Homework01 {public static void main(String[] args) throws FileNotFoundException {String path = "e:\\test\\mytemp";File file = new File(path);if(!file.exists()){file.mkdirs();}else{System.out.println("已存在");}}
}

        

(2)在e:\\mytemp目录下,创建文件hello.txt

记得关闭该字符流

FileWriter fileWriter =null;try {fileWriter = new FileWriter(path + "\\test.txt",true);fileWriter.write("hello,world\n");} catch (IOException e) {e.printStackTrace();}finally {fileWriter.close();}

(3)如果hello.txt已经存在,提示该文件已经存在,就不要再重复创建了

//3)如果hello.txt已经存在,提示该文件已经存在,就不要再重复创建了File file1 = new File(path,"\\hello.txt");FileWriter fileWriter1 =null;try {if(!file1.exists()) {fileWriter1 = new FileWriter(file1);fileWriter1.write("hello,world\n");}else{System.out.println("已存在");}} catch (IOException e) {e.printStackTrace();}finally {if(fileWriter1 != null) {fileWriter1.close();}}

2. 使用处理流

要求:使用BufferedReader读取一 个文本文件,为每行加上行号,再连同内容一并输出到屏幕上。
 

3.使用Properties类的使用

(1)要编写一个dog.properties

        name= tom

        age= 5

        color= red

(2)编写Dog类(name,age.color)创建一 个dog对象, 读取dog.properties 用相应的内容完
成属性初始化,并输出

public class Homework02 {public static void main(String[] args) throws IOException {String path = "e:\\test\\testBufferedCopy.txt";BufferedReader bufferedReader = new BufferedReader(new FileReader(path));int i = 0;String line;while ((line = bufferedReader.readLine()) != null){System.out.println(++i + line);}if(bufferedReader != null){bufferedReader.close();}}
}

3.使用Properties类,使用对象流

(1)要编写一个dog.properties

        name = tom

        age=5

        color= red

(2)编写Dog类(name,age,color)创建一个dog对象, 读取dog.properties 用相应的内容完成属性初始化,并输出

(3)将创建的Dog对象,序列化到文件dog.dat文件

public class Homework03 {public static void main(String[] args) throws IOException, ClassNotFoundException {Properties properties = new Properties();properties.setProperty("name","tom");properties.setProperty("age","50");properties.setProperty("color","red");properties.store(new FileOutputStream("src\\dog.properties"),null);Dog dog = new Dog(properties);ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("e:\\test\\dog.dat"));objectOutputStream.writeObject(dog);objectOutputStream.close();//需要关闭或者刷新才会写入成功ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("e:\\test\\dog.dat"));Object dogInputStream = objectInputStream.readObject();Dog dog1 = (Dog)dogInputStream;System.out.println(dog1);}
}

更多推荐

【JAVA学习笔记】66

本文发布于:2023-11-15 20:34:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1605934.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:学习笔记   JAVA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!