• 文件基础知识和创建文件


    文件基础知识和创建文件

    1. 文件基础知识

    什么是文件?

    • 文件对我们来说并不陌生,文件是保存数据的地方,比如大家经常使用的word文档、text文件、excel文件...都是文件。它既可以保存照片,也可以保存视频、声音...

    文件流

    • 文件在程序中是以流的形式来操作的

    2.创建文件

    创建文件对象相关的构造器和方法

    构造器

    • new File(String pathname):根据路径构建一个File对象
    • new File(String parent,String child):根据父目录+子路径构建一个File对象
    • new File(File parent,String child):根据父目录文件+子路径构建一个File对象

    方法

    • createNewFile():创建新文件

    演示创建文件

    方式1:new File(String pathname)

    1. public class FileCreate {
    2. public static void main(String[] args) {
    3. }
    4. @Test
    5. public void create01(){
    6. String filePath = "d:\\news1.txt";
    7. File file = new File(filePath);
    8. try {
    9. file.createNewFile();
    10. System.out.println("文件创建成功");
    11. } catch (IOException e) {
    12. e.printStackTrace();
    13. }
    14. }
    15. }

    方式2:new File(String parent,String child)

    1. public class FileCreate {
    2. public static void main(String[] args) {
    3. }
    4. @Test
    5. public void create02(){
    6. String parentPath = "d:\\";
    7. String filePath = "news2.txt";
    8. File file = new File(parentPath,filePath);
    9. try {
    10. file.createNewFile();
    11. System.out.println("文件创建成功");
    12. } catch (IOException e) {
    13. e.printStackTrace();
    14. }
    15. }
    16. }

     

    方式3:new File(File parent,String child)

    1. public class FileCreate {
    2. public static void main(String[] args) {
    3. }
    4. @Test
    5. public void create02(){
    6. File parentFile = new File("d:\\");
    7. String filePath = "news2.txt";
    8. File file = new File(parentFile,filePath);
    9. try {
    10. file.createNewFile();
    11. System.out.println("文件创建成功");
    12. } catch (IOException e) {
    13. e.printStackTrace();
    14. }
    15. }
    16. }

     

     

  • 相关阅读:
    服务器虚拟化有什么好处
    【一天一题—Day1】1260. 二维网格迁移
    基于数字电路交通灯信号灯控制系统设计-单片机设计
    GoLong的学习之路(六)语法之指针
    蓝桥杯算法心得——拼数(排列型回溯dfs)
    mysql服务器CPU利用率过高排查
    GPS硬件坐标转百度地图坐标
    SpringBoot篇---第四篇
    antd+react Hook弹窗改进版
    基于离散Markov模型的Web用户行为预测算法的研究
  • 原文地址:https://blog.csdn.net/weixin_52385232/article/details/126133225