栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java Part10 Mission3

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java Part10 Mission3

‎列出用户给定目录下的子目录(子目录不需要输出其中包含的内容)和子文件。如果用户输入的信息不对,则给出“你输入的XXX目录有误。”的提示信息。
import java.io.File;
import java.util.Objects;
import java.util.Scanner;


public class Q1 {
    
    public Q1(String filename) {
        File file = new File(filename);
        if (!file.exists()) {
            System.out.println("你输入的"+file.getName()+"目录有误。");
        } else {
            for (String name : Objects.requireNonNull(file.list())) {
                System.out.println(name);
            }
        }
    }

    public static void main(String[] args) {
        String filename = new Scanner(System.in).nextLine();
        new Q1(filename);
    }
}
使用随机文件流类RandomAccessFile将一个txt文本文件倒序读出显示在控制台。

GBK编码中文占两个字节,UTF-8编码中文三个字节,在本程序中对使用UTF-8的编码的txt文件进行处理。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;


public class Q2 {
    
    public Q2(String filename) throws IOException {
        File file = new File(filename);
        RandomAccessFile raf = new RandomAccessFile(file,"r");
        long length = raf.length();
        StringBuffer buffer = new StringBuffer();
        while (length > 0) {
            length--;
            // 转到length的位置
            raf.seek(length);
            int c = (int)raf.readByte();
            if (c >= 0 && c <= 255) {
                buffer.append((char)c);
            }else {
                // UTF-8编码中文三个字节
                length = length - 2;
                // 对GBK编码的txt文件处理
                // length--;
                raf.seek(length);
                byte[] character = new byte[3];
                // GBK编码
                // byte[] character = new byte[2];
                // 读取中文的三个字节
                raf.read(character);
                buffer.append(new String(character));
            }
        }
        System.out.println(buffer);
    }

    public static void main(String[] args) {
        try {
            new Q2("D:/test.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/327684.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号