java實現目錄
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);
}
}