本帖最后由 光sail 于 2012-4-29 19:38 编辑
从键盘获取目录,列出目录下文件或者文件夹,包含子目录中的内容。也就是列出指定目录下所有内容。- import java.io.File;
- import java.io.InputStream;
- public class ListFile {
- public static void main(String[] args) throws Exception
- {
- String s;
- InputStream in=System.in;
- StringBuilder sb=new StringBuilder();
- while (true){
- int ch=in.read();
- if(ch=='\r')
- continue;
- if(ch=='\n')
- {
- s = sb.toString();
- if("over".equals(s))
- break;
- sb.delete(0,sb.length());
- }
- else
- sb.append((char)ch);
- }
- File file=new File(sb.toString());
- showFile(file,0);
- }
- public static String getLevel(int Level){
- StringBuilder sb=new StringBuilder();
- sb.append("|--");
- for (int i = 0; i < Level; i++) {
- sb.insert(0, "| ");
- }
- return sb.toString();
- }
- public static void showFile(File dir,int level){
- System.out.println(getLevel(level)+dir.getName());
- level++;
- File [] files=dir.listFiles();
- for (int i = 0; i < files.length; i++) {
- if(files[i].isDirectory())
- showFile(files[i],level);
- else
- System.out.println(getLevel(level)+files[i]);
- }
- }
- }
复制代码 键盘录入结束后抛出个异常 Exception in thread "main" java.lang.NullPointerException
at ListFile.showFile(ListFile.java:47)
at ListFile.main(ListFile.java:33)
大家帮帮忙看看
|