当前位置:首页 » 知网查重 » java实现目录

java实现目录

发布时间: 2021-03-05 16:11:53

1. java编写程序实现将指定的目录以及其子文件和子目录全部删除

下面是对文件以及文件夹的删除操作!你选一个试试
其中%%1代表你文件的路径。
删除文件
File myDelFile = new File(%%1);
try {
myDelFile.delete();
}
catch (Exception e) {
System.out.println("删除文件操作出错");
e.printStackTrace();
}
.删除文件夹
//import java.io.*;
File delFolderPath = new File(%%1);
try {
delFolderPath.delete(); //删除空文件夹
}
catch (Exception e) {
System.out.println("删除文件夹操作出错");
e.printStackTrace();
}
.删除一个文件下夹所有的文件夹
//import java.io.*;
File delfile=new File(%%1);
File[] files=delfile.listFiles();
for(int i=0;i<files.length;i++){
if(files[i].isDirectory()){
files[i].delete();
}
}

清空文件夹
//import java.io.*;
File delfilefolder=new File(%%1);
try {
if (!delfilefolder.exists()) {
delfilefolder.delete();
}
delfilefolder.mkdir();
}
catch (Exception e) {
System.out.println("清空目录操作出错");
e.printStackTrace();
}

2. Java实现读取某个路径下的文件目录

importjavax.swing.*;

importjavax.swing.table.AbstractTableModel;

importjavax.swing.table.TableCellRenderer;

importjavax.swing.event.TreeModelListener;

importjavax.swing.event.TreeSelectionListener;

importjavax.swing.event.TreeSelectionEvent;

importjavax.swing.tree.TreeModel;

importjavax.swing.tree.TreePath;

importjavax.swing.tree.TreeCellRenderer;

importjava.awt.*;

importjava.awt.event.*;

importjava.io.File;

importjava.io.FileInputStream;

importjava.io.IOException;

importjava.io.FileFilter;

importjava.util.Calendar;

importjava.util.ArrayList;

importjava.text.SimpleDateFormat;

importjava.text.MessageFormat;

/**

*@authorHardneedl

*/

{

=newDimension(300,200);

=newDimension(1024,768);

=newDimension(600,400);

privateJLabelstatusLabel;

privateJTreetree;

privateJTabledetailTable;

;

publicDimensiongetMaximumSize(){returnmaxSize;}

publicDimensiongetMinimumSize(){returnminSize;}

(){returnpreferredSize;}

publicStringgetTitle(){return"JavaExplorer";}

JavaExplorer()throwsHeadlessException{

init();

doLay();

attachListeners();

}

privatevoidinit(){

statusLabel=newJLabel(){publicColorgetForeground(){returnColor.BLUE;}};

tree=newJTree(newFileTreeModel());

tree.setCellRenderer(newDirCellRenderer());

detailTable=newJTable(tableModel=newFileTableModel());

detailTable.getColumnModel().getColumn(2).setCellRenderer(newTableCellRenderer(){

privateJLabellabel=newJLabel();

=newSimpleDateFormat("yyyy年mm月dd日HH时MM分ss秒");

(JTabletable,Objectvalue,booleanisSelected,booleanhasFocus,introw,intcolumn){

if(valueinstanceofCalendar){

Calendarcal=(Calendar)value;

label.setText(format.format(cal.getTime()));

}

returnlabel;

}

});

detailTable.getColumnModel().getColumn(0).setCellRenderer(newTableCellRenderer(){

privateJLabellabel=newJLabel();

(JTabletable,Objectvalue,booleanisSelected,booleanhasFocus,introw,intcolumn){

if(valueinstanceofFile){

Filef=(File)value;

label.setText(f.getName());

label.setForeground(f.isDirectory()?Color.RED:Color.BLACK);

}

returnlabel;

}

});

}

privatevoiddoLay(){

Containercontainer=getContentPane();

JSplitPanesplitPane=newJSplitPane(JSplitPane.HORIZONTAL_SPLIT,newJScrollPane(tree),newJScrollPane(detailTable));

container.add(splitPane,BorderLayout.CENTER);

container.add(statusLabel,BorderLayout.SOUTH);

pack();

}

privatevoidattachListeners(){

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

tree.addTreeSelectionListener(newSelectionListener());

tree.addTreeSelectionListener(new_DirSelectionListener());

DirCellSelectedListenerck=newDirCellSelectedListener(tree);

detailTable.addKeyListener(ck);

detailTable.addMouseListener(ck);

}

publicstaticvoidmain(String[]args){

newJavaExplorer().setVisible(true);

}

{

staticfinalStringroot="我的电脑";

privateFile[]rootFiles;

=newFileFilter(){

publicbooleanaccept(Filef){returnf.isDirectory();}

};

privateFileTreeModel(){rootFiles=File.listRoots();}

publicObjectgetRoot(){returnroot;}

publicObjectgetChild(Objectparent,intindex){

if(parent==getRoot())returnrootFiles[index];

if(parentinstanceofFile){

Filepf=(File)parent;

returnpf.listFiles(dirFilter)[index];

}

returnnull;

}

publicintgetChildCount(Objectparent){

if(parent==getRoot())returnrootFiles.length;

if(parentinstanceofFile){

Filepf=(File)parent;

File[]fs=pf.listFiles(dirFilter);

returnfs==null?0:fs.length;

}

return0;

}

publicbooleanisLeaf(Objectnode){returnfalse;}

publicvoidvalueForPathChanged(TreePathpath,ObjectnewValue){}

(TreeModelListenerl){}

(TreeModelListenerl){}

publicintgetIndexOfChild(Objectparent,Objectchild){

if(parent==getRoot()){

for(inti=0,j=rootFiles.length;i<j;i++)

if(rootFiles[i]==child)returni;

}

if(parentinstanceofFile){

Filepf=(File)parent;

File[]fs=pf.listFiles(dirFilter);

for(inti=0,j=fs.length;i<j;i++){

if(fs[i].equals(child))returni;

}

}

return-1;

}

}

{

publicintgetRowCount(){returndir==null||dir.isFile()?0:dir.listFiles().length;}

publicintgetColumnCount(){return3;}

privateFiledir;

privatevoidsetDir(Filedir){

this.dir=dir;

fireTableDataChanged();

}

publicClass<?>getColumnClass(intcolumnIndex){

switch(columnIndex){

case0:returnFile.class;

case1:returnInteger.class;

case2:returnCalendar.class;

default:returnString.class;

}

}

publicStringgetColumnName(intcolumn){

switch(column){

case0:return"名称";

case1:return"大小";

case2:return"修改日期";

default:return"";

}

}

publicObjectgetValueAt(introwIndex,intcolumnIndex){

File[]fs=dir.listFiles();

Filef=fs[rowIndex];

switch(columnIndex){

case0:returnf;

case1:

if(f.isDirectory())returnnull;

try{

if(f.canRead())

returnnewFileInputStream(f).available();

}catch(IOExceptione){

e.printStackTrace();

}

case2:

Calendarcl=Calendar.getInstance();

cl.setTimeInMillis(f.lastModified());

returncl;

}

returnnull;

}

}

privateclass_{

publicvoidvalueChanged(TreeSelectionEvente){

TreePathpath=e.getNewLeadSelectionPath();

if(path!=null){

Objectobj=path.getLastPathComponent();

if(objinstanceofFile){

Filef=(File)obj;

File[]fs=f.listFiles();

statusLabel.setText(fs==null?null:MessageFormat.format("{0}个文件",fs.length));

}

else

statusLabel.setText(null);

}

}

}

{

publicbooleanisOpaque(){returntrue;}

(JTreetree,Objectvalue,booleanselected,booleanexpanded,booleanleaf,introw,booleanhasFocus){

if(valueinstanceofFile){

Strings=((File)value).getName();

setText(s.isEmpty()?value.toString():s);

}

else

setText(value.toString());

setForeground(selected?Color.BLUE:Color.BLACK);

setBackground(selected?Color.YELLOW:Color.WHITE);

returnthis;

}

}

{

publicvoidvalueChanged(TreeSelectionEvente){

Objectobj=e.getNewLeadSelectionPath().getLastPathComponent();

if(objinstanceofFile){

tableModel.setDir((File)obj);

}

}

}

,MouseListener{

privateJTreetree;

(JTreet){tree=t;}

privatevoidaction(InputEvente){

if(einstanceofMouseEvent){

}

if(einstanceofKeyEvent){

}

}

privatevoidexpand(Filef){

if(f.isDirectory()){

ArrayList<File>L=newArrayList<File>();

L.add(f);

FileparentFile=f.getParentFile();

while(parentFile!=null){

L.add(parentFile);

parentFile=parentFile.getParentFile();

}

TreePathtreePath=newTreePath(FileTreeModel.root);

for(inti=L.size()-1;i>-1;i--){

treePath=treePath.pathByAddingChild(L.get(i));

}

tree.setSelectionPath(treePath);

}

}

publicvoidkeyTyped(KeyEvente){}

publicvoidkeyPressed(KeyEvente){

if(e.getKeyCode()!=KeyEvent.VK_ENTER)return;

if(e.getSource()==detailTable){

introw=detailTable.getSelectedRow();

if(row!=-1){

Filef=(File)detailTable.getValueAt(row,0);

expand(f);

}

}

}

publicvoidkeyReleased(KeyEvente){

}

publicvoidmouseClicked(MouseEvente){

if(e.getClickCount()==2){

if(e.getSource()==detailTable){

introw=detailTable.getSelectedRow();

if(row!=-1){

Filef=(File)detailTable.getValueAt(row,0);

expand(f);

}

}

}

}

publicvoidmousePressed(MouseEvente){

}

publicvoidmouseReleased(MouseEvente){

}

publicvoidmouseEntered(MouseEvente){

}

publicvoidmouseExited(MouseEvente){

}

}

}

3. 用java写一个代码实现: 如何列出某个目录下的所有子目录

||/**
* 列出文件夹下的子文件夹名
* @param localRoot
* @throws content
*/
public static void list(String localRoot) throws Exception {
File[] fs = new File(localRoot).listFiles();
if ((fs == null) || (fs.length <= 0)) {
System.out.println("空文件夹");
return;
}
for (File f : fs) {
if (f.isDirectory()) {
System.out.println("目录:"+ f.getName());
}
}
}

建立个class然后见个main方法调用一内下就容可以了!

4. 求助在java里实现树形目录

给你一个读取目录结构,生成字符串的程序参考一下吧。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileFilter;
import java.util.HashMap;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class PathTree extends JPanel {
private static final long serialVersionUID = 1L;

private JButton stopButton = new JButton("停止扫描");
private JButton browseButton = new JButton("选择文件夹");
private JTextArea pathsTextArea = new JTextArea();
private JCheckBox showHiddenFilesCheckbox = new JCheckBox("显示隐藏文件", false);

private Map<Integer, String> pathIndexes = new HashMap<Integer, String>();
private FileFilter docFilter = new DocFilter(); // 文档过滤器
private FileFilter dirFilter = new DirFilter(); // 文件夹过滤器

private boolean stopped = false; // 是否停止扫描的标志

public PathTree() {
initGui();
}

// 初始化界面
private void initGui() {
this.setLayout(new BorderLayout());

JPanel buttonsPanel = new JPanel();
buttonsPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY));
buttonsPanel.add(showHiddenFilesCheckbox);
buttonsPanel.add(browseButton);
buttonsPanel.add(stopButton);
this.add(buttonsPanel, BorderLayout.NORTH);

JScrollPane scroller = new JScrollPane(pathsTextArea);
scroller.setBorder(null);
this.add(scroller, BorderLayout.CENTER);

browseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 选择文件夹
final JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = chooser.showOpenDialog(PathTree.this);

if (result == JFileChooser.APPROVE_OPTION) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
File dir = chooser.getSelectedFile();
pathsTextArea.setText("");
stopped = false;
walkTree(dir, 0);
}
});
t.start();
}
}
});

stopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stopped = true;
}
});
}

// 递归遍历目录树
private void walkTree(File dir, int level) {
// 1. current dir path
// 2. docs path that located in this dir
// 3. sub dirs path

if (stopped) { return; }

// 如果不显示隐藏文件,则返回
if (dir.isHidden() && !showHiddenFilesCheckbox.isSelected()) { return; }

final StringBuilder pathBuffer = new StringBuilder(1024);

// 访问当前目录
pathBuffer.append(createPath(dir, level));

// 访问文档
for (File doc : dir.listFiles(docFilter)) {
if (doc.isHidden() && !showHiddenFilesCheckbox.isSelected()) {
continue;
}
pathBuffer.append(createPath(doc, level + 1));
}

// 把当前目录下的文件更新到text area中
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
pathsTextArea.append(pathBuffer.toString());
}
});

// 递归遍历子目录
for (File subDir : dir.listFiles(dirFilter)) {
walkTree(subDir, level + 1);
}
}

// 创建文件的路径
public String createPath(File file, int level) {
StringBuilder pathBuffer = new StringBuilder(128);
pathBuffer.append(getPathIndex(level)).append(file.getName()).append("\n");

return pathBuffer.toString();
}

// 创建目录的缩进
private String getPathIndex(int level) {
// 如果不存在,则创建
if (pathIndexes.get(level) == null) {
StringBuilder indexBuffer = new StringBuilder(128);
for (int i = 0; i < level; ++i) {
indexBuffer.append("| ");
}

indexBuffer.append("|----");
pathIndexes.put(Integer.valueOf(level), indexBuffer.toString());
return indexBuffer.toString();
} else {
return pathIndexes.get(level);
}
}

// 创建主窗口
private static void createGUIAndShow() {
JFrame frame = new JFrame("目录结构树");
frame.setContentPane(new PathTree());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();
int w = 600;
int h = 700;
int x = (ss.width - w) / 2;
int y = (ss.height - h) / 2 - 40;
x = x > 0 ? x : 0;
y = y > 0 ? y : 0;
frame.setBounds(x, y, w, h);
frame.setVisible(true);
}

public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
//UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}

SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createGUIAndShow();
}
});
}
}

class DocFilter implements FileFilter {
@Override
public boolean accept(File file) {
return file.isFile();
}
}

class DirFilter implements FileFilter {
@Override
public boolean accept(File file) {
return file.isDirectory();
}
}

这是生成的目录树结构:
|----Desktop
| |----3D数学基础_图形与游戏开发.pdf
| |----Hibernate与IBatis的优缺点及可行性分析2.txt
| |----Hibernate和iBatis比较.txt
| |----深入理解O:R Mapping - Hibernate - Java - JavaEye论坛.webarchive
| |----地下管线安全管理系统
| | |----创造三大价值,让收益更加显著1_resize.jpg
| | |----创造三大价值,让收益更加显著_resize.jpg
| | |----永安集成管理系统_resize.jpg
| | |----系统实现流程_resize.jpg
| | |----自主创新,于创新中超越_resize.jpg
| | |----行业领先功能,解决四大问题_resize.jpg
| | |----解决地下管线行业难题_resize.jpg

5. 如何用Java实现列出某个目录下的所有子目录

/**
* 列出文件夹下的子文件夹名
* @param localRoot
* @throws content
*/
public static void list(String localRoot) throws Exception {
File[] fs = new File(localRoot).listFiles();
if ((fs == null) || (fs.length <= 0)) {
System.out.println("空文件夹");
return;
}
for (File f : fs) {
if (f.isDirectory()) {
System.out.println("目录:"+ f.getName());
}
}
}

建立个class然后见个main方法调用内一下就可容以了!

6. Java目录处理

Java代码:

publicclassMain{
publicstaticvoidmain(String[]args){
Stringsource="./src/../bin/./target";
StringBuildersb=newStringBuilder(source);
Stringpath=null;
intpre,curr,next;

//处理“/..”
while((curr=sb.indexOf("/.."))>=0){
pre=sb.substring(0,curr).lastIndexOf("/"); //curr之前的最后一个“/”
next=curr+1+sb.substring(curr+1).indexOf("/"); //curr之后的第一个“/”
sb.delete(pre,next); //删除“/..”及上一级目录名称
}

//处理多余的“/.”
while((curr=sb.indexOf("/."))>=0){
sb.delete(curr,curr+2);
}

System.out.println("处理后的目录:"+sb.toString());
}
}


运行测试:

处理后的目录:./bin/target

7. java怎么创建目录代码实例

public void newFolder(String folderPath) {
try {
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
if (!myFilePath.exists()) {
myFilePath.mkdir();
}
}
catch (Exception e) {
System.out.println("新建目录操作出版错权");
e.printStackTrace();
}
}

8. java 实现浏览目录

刚好昨天无聊时写了一个试试。主要功能实现了,你要想美化一点外观的话就内去看看容API吧。^_^。
import java.io.File;
import javax.swing.JFileChooser;

public class JFileChooserTest
{
public static void main(String[] args)
{
File f = new File("");
f = f.getAbsoluteFile();
JFileChooser jfc = new JFileChooser(f);
jfc.showOpenDialog(null);
File f2 = jfc.getSelectedFile();
System.out.println(f2);
jfc.setVisible(true);
}
}

9. 目录结构是怎么实现的 java

* @param path 目标文件路径

* @param content 需要写入的内容

* @return 写入结果

*/

public static boolean writeToFile(String path, String content)

{

final int CACHE = 1024;

boolean result = false;

FileOutputStream outFile = null;

FileChannel channel = null;

// 将字符串转换为字节数组

final byte[] bt = content.getBytes();

ByteBuffer buf = null;

try

{

outFile = new FileOutputStream(path);

channel = outFile.getChannel();

// 以指定的缓存分隔字节数组,得到缓存次数

int size = bt.length / CACHE;

// 得到被缓存分隔后剩余的字节个数

int mod = bt.length % CACHE;

int start = 0;

int end = 0;

for(int i = 0; i < size + 1; i++)

{

if(i == size)

{

if(mod > 0)

{

// 分配新的字节缓冲区

buf = ByteBuffer.allocate(mod);

start = end;

end += mod;

}

else

{

break;

}

}

else

{

// 分配新的字节缓冲区

buf = ByteBuffer.allocate(CACHE);

start = end;

end = (i + 1) * CACHE;

}
// 反转缓冲区,为通道写入做好准备

buf.flip();

// 利用通道写入文件

channel.write(buf);

result = true;

}

}

catch(IOException e)

{

e.printStackTrace();

}

finally

{

// 关闭所有打开的IO流

try

{

channel.close();

outFile.close();

}

catch(IOException e)

{

e.printStackTrace();

}

}

return result;

}

/**

* 以指定的始末位置从字节数组中获取其子数组

* @param bt 原始字节数组

* @param start 起始位置

* @param end 结束位置

* @return 子字节数组

*/

private static byte[] getSubBytes(byte[] bt, int start, int end)

{

int size = end - start;

byte[] result = new byte[size];

for(int i = 0; i < size; i++)

{

result[i] = bt[i + start];

}

return result;

}

// 以指定的始末位置获取一个缓存大小的字节

byte[] bytes = getSubBytes(bt, start, end);

for(int j = 0; j < bytes.length; j++)

{

buf.put(bytes[j]);

10. java创建目录

贴上正确代码:你的代码本来没有什么问题的,但是只能够通过DOS下去运行,如果要在eclipse这些工具运行只能在arguments里面输入参数,谢谢采纳
import java.io.*;
import java.util.Scanner;

public class Exceptle13_1 {
public void newFolder(String newfolder) {
try {
String filepath = newfolder;
File myPath = new File(filepath);
if (!myPath.exists()) {
myPath.mkdir();
}
} catch (Exception e) {
System.out.println("新建目录存在");
e.printStackTrace();
}
}

public static void main(String[] args) {
String mynewpath = new Scanner(System.in).next();
System.out.println(mynewpath);
Exceptle13_1 createNewFolder = new Exceptle13_1();
createNewFolder.newFolder(mynewpath);
}

}

热点内容
涂鸦论文 发布:2021-03-31 13:04:48 浏览:698
手机数据库应用 发布:2021-03-31 13:04:28 浏览:353
版面217 发布:2021-03-31 13:04:18 浏览:587
知网不查的资源 发布:2021-03-31 13:03:43 浏览:713
基金赎回参考 发布:2021-03-31 13:02:08 浏览:489
悬疑故事范文 发布:2021-03-31 13:02:07 浏览:87
做简单的自我介绍范文 发布:2021-03-31 13:01:48 浏览:537
战略地图参考 发布:2021-03-31 13:01:09 浏览:463
收支模板 发布:2021-03-31 13:00:43 浏览:17
电气学术会议 发布:2021-03-31 13:00:32 浏览:731