| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1252 人关注过本帖
标题:我是Java初学者,遇到swing的习题,敲完发现很多问题,求纠正
只看楼主 加入收藏
苏憨憨
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2020-12-28
收藏
 问题点数:0 回复次数:0 
我是Java初学者,遇到swing的习题,敲完发现很多问题,求纠正
[这是题目4.功能较完善的文件管理器实现一个能够对文件和文件夹进行各种基本操作的文件管理器窗口程序。功能要求:1)新建、删除、修改、复制、黏贴文件功能2)新建、删除、修改目录3)具有对某个文件进行压缩打包的功能4)要求实现多文档界面5)要求界面美观、功能布局合理。

这是代码   拜托大家看看
/////////////// scaner类/////////////////////
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import *;
import java.util.*;
public class scaner extends JFrame
implements ActionListener,TreeExpansionListener,TreeSelectionListener
{
/**
*
*/
private static final long serialVersionUID = -6653169472316161951L;
//定义常量
JTree jtree = new JTree(createTreeModel());
JPanel JPsub=new JPanel(new GridLayout(0,1));
JPanel road=new JPanel(new BorderLayout());
JFrame f,ff;
JSplitPane JSP; //可滚动
JButton sure,ok;
JLabel status=new JLabel(" ");
JLabel shijian,size;
JTextField renamest,zipname;
GregorianCalendar time = new GregorianCalendar();
int hour = time.get(Calendar.HOUR_OF_DAY);
int min = time.get(Calendar.MINUTE);
int second = time.get(Calendar.SECOND);
Vector<String> v;
JToolBar statusBar;
JPopupMenu popupMenu;
JMenuItem  popupMenu_Copy,  popupMenu_Delete,newfiles,p_zip;
JMenuItem copy,del;
JMenu m1, m2, m3;
JMenuItem newItem, exitItem, zuozhe, help;
JButton btt;
JList F_list;
PopupMenu menu;
MenuItem b_open, b_copy, b_jiantie, b_del,newfile,b_rename,b_Zip,newfload;
Object[] dizhi;
FileDialog fd;
long sizes;
String newname;
//构造函数
public scaner()
{
super("文件管理器");
//设置窗口大小
Container container = getContentPane();///时钟布局
int i = 400;
int j = 100;
FileDialog fd;
long sizes;
String newname;
//构造函数
public scaner()
{
super("文件管理器");
//设置窗口大小
Container container = getContentPane();///时钟布局
int i = 400;
int j = 100;
setBounds(i,j,840,580);
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent windowevent)
{
System.exit(0);
}
}
);
////////////////////////////////////////////////////////////
m1 = new JMenu("文件") ;
m2 = new JMenu("编辑") ;
m3 = new JMenu("帮助") ;
JMenuBar menuBar = new JMenuBar() ;
menuBar.add(m1) ;
menuBar.add(m2) ;
menuBar.add(m3) ;
newItem = new JMenuItem("新建文件") ;
exitItem = new JMenuItem("退出") ;
// 此时定义完了四个菜单的选项,定义完成之后,增加快捷键
newItem.setMnemonic('N') ;
exitItem.setMnemonic('E') ;
newItem.setAccelerator(KeyStroke.getKeyStroke('N',java.awt.Event.CTRL_MASK)) ;
exitItem.setAccelerator(KeyStroke.getKeyStroke('E',java.awt.Event.ALT_MASK)) ;
newItem.addActionListener(this); ///注册监听器
exitItem.addActionListener(this);
m1.add(newItem) ;
m1.add(exitItem) ;
/////////////////////////////
copy = new JMenuItem("复制") ;
del = new JMenuItem("删除") ;
// 此时定义完了两个菜单的选项,定义完成之后,增加快捷键
copy.setMnemonic('C') ;
copy.setAccelerator(KeyStroke.getKeyStroke('C',java.awt.Event.ALT_MASK)) ;
m2.add(copy) ;

m2.add(del) ;
copy.addActionListener(this);
del.addActionListener(this);
/////////////////////////
zuozhe = new JMenuItem("关于") ;
help = new JMenuItem("帮助");
m3.add(help);
m3.add(zuozhe);
zuozhe.addActionListener(this);
help.addActionListener(this);
////////////////////////////////
setJMenuBar(menuBar) ;    // 菜单是需要通过此方法增加的
setVisible(true) ;
//frame.setSize(700,500) ;
setLocation(300,200);
////////////////////////////////////////////////////
// -------------------创建右键弹出菜单
popupMenu = new JPopupMenu();
newfiles=new JMenuItem("新建文件夹");
popupMenu_Copy = new JMenuItem("复制(C)", 'C');
popupMenu_Delete = new JMenuItem("删除(D)", 'D');
p_zip =new JMenuItem("添加到压缩文件");
// ---------------向右键菜单添加菜单项和分隔符
popupMenu.addSeparator();
popupMenu.add(newfiles);
popupMenu.add(popupMenu_Copy);
popupMenu.add(p_zip);
popupMenu.add(popupMenu_Delete);
popupMenu.addSeparator();
// --------------------右键菜单注册事件

popupMenu_Copy.setActionCommand("复制(C)");
popupMenu_Copy.addActionListener(this);
popupMenu_Delete.setActionCommand("删除(D)");
popupMenu_Delete.addActionListener(this);
newfiles.setActionCommand("新建文件夹");
newfiles.addActionListener(this);
p_zip.addActionListener(this);
jtree.add(popupMenu);
/////////////////////////////////////////////////////////////
menu = new PopupMenu();
newfload=new MenuItem("新建文件夹");
newfile=new MenuItem("新建文件");
b_open=new MenuItem("打开");
b_copy=new MenuItem("复制");
b_Zip=new MenuItem("添加到压缩文件");
b_del=new MenuItem("删除");
b_rename=new MenuItem("重命名");
menu.addSeparator();
menu.add(b_open);
menu.add(newfload);
menu.add(newfile);
menu.add(b_copy);
menu.add(b_Zip);
menu.add(b_rename);
menu.add(b_del);
menu.addSeparator();
b_open.addActionListener(this);
newfload.addActionListener(this);
b_copy.addActionListener(this);
b_del.addActionListener(this);
b_Zip.addActionListener(this);
b_rename.addActionListener(this);
newfile.addActionListener(this);
JPsub.add(menu);
//////////////////////////////////////////////////////////////
//水平分割窗口,左scrollPane内放tree,右放JPsub用于显示文件
JSP=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(jtree),new JScrollPane(JPsub));
JSP.setDividerLocation (200);////////设置分隔条的位置。
JSP.setLastDividerLocation(200); /////// 将分隔条所处的最后位置设置为newLastLocation。
getContentPane().add(JSP);
//背景色为白
JPsub.setBackground(Color.white);
//////////////////////////////////////
/////////////////////////////////////////////时间///////////////////////
statusBar = new JToolBar();
shijian = new JLabel("    当前时间:" + hour + ":" + min + ":" + second);
statusBar.addSeparator();
statusBar.add(shijian);
statusBar.setVisible(true);
container.add(statusBar, BorderLayout.SOUTH);
statusBar.setVisible(true);
//////////////////////////////////////////////
//给树添加展开监听器
jtree.addTreeExpansionListener(this);
jtree.addTreeSelectionListener(this);
//设置树的外形 ,改变文件夹的图案
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
}
catch (Exception ex) {}
jtree.setShowsRootHandles(true);
getContentPane().add(road,BorderLayout.NORTH);
road.add(status,BorderLayout.WEST); ///西边....左边
Clock clock=new Clock();////线程
clock.start();
//////////////////////////////////////////////////
f = new JFrame("重命名") ;
f.setSize(230,80) ;    // 设置组件的大小
f.setBackground(Color.WHITE) ;    // 将背景设置成白色
f.setLocation(300,200) ;    // 设置组件的显示位置

renamest=new JTextField();
sure=new JButton("确定");
f.add(renamest,BorderLayout.CENTER);
f.add(sure,BorderLayout.SOUTH);
sure.addActionListener(this);
//////////////////////////////////////////////////
ff = new JFrame("压缩文件名") ;
ff.setSize(230,80) ;    // 设置组件的大小
ff.setBackground(Color.WHITE) ;    // 将背景设置成白色
ff.setLocation(300,200) ;    // 设置组件的显示位置
zipname=new JTextField();
ok=new JButton("确定");
ff.add(zipname,BorderLayout.CENTER);
ff.add(ok,BorderLayout.SOUTH);
ok.addActionListener(this);
}
////////////实现复制,黏贴功能////////////////////////////
class MainFrame extends JFrame
{
/**
*
private static final long serialVersionUID = 1L;
*/
public MainFrame()
{
super("COPY");
setDefaultCloseOperation(HIDE_ON_CLOSE);
setSize(500,260);
setLocation(300,200) ;
MainPanel pan = new MainPanel();
setContentPane(pan);
setLayout(null);
}
}
class MainPanel extends JPanel
{
/**
*
*/
private static final long serialVersionUID = 1L;
JTextField txt;
JTextArea txtInFile;
JTextArea txtOutFile;
JFileChooser open;
String strFilePath;
String strFilePathCopyTo;
public MainPanel()
{
JLabel lblIn = new JLabel("源文件:");
lblIn.setBounds(30, 65, 50, 20);
if(F_list.isSelectionEmpty())
txtInFile = new JTextArea(zhantie());
else
txtInFile = new JTextArea(zhantie()+F_list.getSelectedValue());
JScrollPane scrint = new JScrollPane(txtInFile) ;
JButton btnSelect = new JButton("选择文件或目录");
scrint.setBounds(80,65,265,40);
btnSelect.setBounds(350, 65, 120, 20);
open = new JFileChooser();/////////////////////
txtInFile = new JTextArea(zhantie()+F_list.getSelectedValue());
open.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
open.setCurrentDirectory(new File(zhantie()));
btnSelect.addActionListener(new ActionListener()
{
@SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e)
{
open.showOpenDialog(null);
strFilePath = open.getSelectedFile().getPath();///源文件路径
((JButton)e.getSource()).setLabel("已选");
txtInFile.setText(strFilePath);
System.out.println(txtInFile.getText());
System.out.println("打开文件");
}
}
);
JLabel lblOut = new JLabel("复制到:");
txtOutFile = new JTextArea();
lblOut.setBounds(30, 125, 50, 20);
txtOutFile = new JTextArea();
txtOutFile.setBounds(80,60,100,20);
JScrollPane scrout = new JScrollPane(txtOutFile) ;
scrout.setBounds(80,125,265,40);
JButton btnSelectCopyTo = new JButton("选择目标路径");
btnSelectCopyTo.setBounds(350, 125, 120, 20);
btnSelectCopyTo.addActionListener(new ActionListener()
{
@SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e)
{
if(F_list.isSelectionEmpty())
open.setSelectedFile(new File(zhantie()));
else
open.setSelectedFile(new File(zhantie()+F_list.getSelectedValue()));
open.showSaveDialog(null);
strFilePathCopyTo = open.getSelectedFile().getPath();
((JButton)e.getSource()).setLabel("已选");
txtOutFile.setText(strFilePathCopyTo);
System.out.println(txtOutFile.getText());
System.out.println("打开文件");
}
}
);
JButton btnCopy = new JButton("开始复制");
btnCopy.setBounds(130, 180, 90, 20);
btnCopy.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
strFilePath = txtInFile.getText();
strFilePathCopyTo = txtOutFile.getText();
System.out.println(strFilePath);
System.out.println(strFilePathCopyTo);
IOTest.copyFile(strFilePath, strFilePathCopyTo);
}
});
add(lblIn);
add(scrint);
add(btnSelect);
add(lblOut);
add(scrout);
add(btnSelectCopyTo);
add(btnCopy);
}
}
////////////////////////////////////////////////////////
//树展开
public void treeExpanded(TreeExpansionEvent e) /////监听,当树扩展或折叠某一节点时获得通知的侦听器
{
//getLastSelectedPathComponent()返回当前选择的第一个节点中的最后一个路径组件。
//首选节点的 TreePath 中的最后一个Object,若未选择任何内容,则返回 null
if (jtree.getLastSelectedPathComponent()==null)
return;
if (jtree.getLastSelectedPathComponent().toString().trim().equals("我的电脑"))
return;
TreePath tpath = e.getPath();
FileNode node = (FileNode)tpath.getLastPathComponent(); ///返回此路径的最后一个组件
if( ! node.isExplored())
{
DefaultTreeModel model = (DefaultTreeModel)jtree.getModel();
node.Explore();
model.nodeStructureChanged(node); ///如果完全更改了节点的子节点、子节点的子节点、依此类推,则调用此方法
}
}
//树折叠
public void treeCollapsed(TreeExpansionEvent e) {}
////////////////////////////////////////////////////////////////
//值变化
public void valueChanged(TreeSelectionEvent e)
{
try{
//如果该结点最后一个对象返回值为空,即为底层结点,返回,清空JPsub
if (jtree.getLastSelectedPathComponent()==null)
return;
JPsub.removeAll();
//如果是本地,则产生目录
if (jtree.getLastSelectedPathComponent().toString().trim().equals("我的电脑"))
{
for(int i=0;i <roots.length;i++)
File roots[]=File.listRoots();//硬盘的名字
{
v = new Vector<String>() ;///向量
String DiskName=roots[i].toString();
v.add(roots[i].toString());
DiskName=DiskName.substring(0,DiskName.indexOf(":")+1);
addlist(v);
}
}
else
{
Object []path= e.getPath().getPath();
String st="";
for(int i=1;i <path.length;i++)
st+=File.separator+path[i].toString();
File f = new File(st.substring(1));
status.setText(f.toString()); ///Label
String[] list= f.list(); ///返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录
//定义Vector变量 ,创建向量类Vector
Vector<Object> vFile=new Vector<Object>(),vDir=new Vector<Object>();
for(int i = 0; i < list.length; i++)
{
if ((new File(st+File.separator+list[i])).isDirectory()) //测试是否是目录
vDir.addElement(list[i]);
else
vFile.addElement(list[i]);
}
//排序
sortElements(vFile);
sortElements(vDir);
v = new Vector<String>() ;///向量
for(int i=0;i <vDir.size();i++)
v.add((String)(vDir.elementAt(i))); ///文件夹
for(int i=0;i <vFile.size();i++)
v.add((String)(vFile.elementAt(i))); //文件         
}
addlist(v);
JPsub.doLayout(); /// 提示布局管理器布局此组件。
JPsub.repaint(); ////重绘此组件。
}
catch(Exception ee){}
}
//交换
private void swap(int loc1,int loc2,Vector<Object> v)
{
Object tmp=v.elementAt(loc1);
v.setElementAt(v.elementAt(loc2),loc1);
v.setElementAt(tmp,loc2);
}
//排序

public void sortElements(Vector<Object> v)
{
for(int i=0;i <v.size();i++)
{
int k=i;
for(int j=i+1;j <v.size();j++)
if(((String)(v.elementAt(j))).toLowerCase().compareTo(((String)(v.elementAt(k))).toLowerCase()) <0)
k=j;
if(k!=i)swap(k,i,v);//进行交换
}
}
public void addlist(Vector<String> v)///右边文件列表
{
F_list=new JList(v);
JPsub.add(F_list);
F_list.addMouseListener(new MouseAdapter(){//////////鼠标事件监听
public void mousePressed(MouseEvent e)
{
int index=F_list.locationToIndex(e.getPoint());//右键选中
F_list.setSelectedIndex(index);
}      
public void mouseClicked(MouseEvent e)
{
int index;
if(e.getButton()==3)
{
menu.show(F_list, e.getX(), e.getY());//右键菜单
}
else if (e.getSource()==F_list)
{
if (e.getClickCount()==2)
{
try
{
TreePath p=jtree.getLeadSelectionPath();
String text=F_list.getSelectedValue().toString();
Object []path= p.getPath();
String sr="";
for(int i=1;i <path.length;i++)
sr+=File.separator+path[i].toString();
sr=sr.substring(1);
File f = new File(sr+File.separator+text);
status.setText(f.toString());
if(f.isDirectory())
{
index=jtree.getRowForPath(p);
jtree.expandRow(index);
while (!(jtree.getLastSelectedPathComponent().toString().trim().equals(text)))
jtree.setSelectionRow(index++);
jtree.expandRow(index-1);
if(postfix.indexOf(".TXT")!=-1||postfix.indexOf(".JAVA")!=-1||
}
else
{
String postfix=text.toUpperCase();
if(postfix.indexOf(".TXT")!=-1||postfix.indexOf(".JAVA")!=-1||
postfix.indexOf(".HTM")!=-1||postfix.indexOf(".LOG")!=-1||postfix.indexOf(".CPP")!=-1)
Runtime.getRuntime().exec("NotePad.exe "+sr+File.separator+text);
else if(postfix.indexOf(".DOC")!=-1)
{
Runtime.getRuntime().exec("c:\\Program Files\\Microsoft Office\\Office14\\WINWORD.EXE .\\"+sr+File.separator+text);
}
}
}
catch(Exception ee){}
}
}   
}
});
jtree.addMouseListener(new MouseAdapter() {///jtree右键监听
public void mousePressed(MouseEvent e) {
if (e.getButton() == 3) {  //鼠标右键
popupMenu.show(e.getComponent(),e.getX(),e.getY());
}
}
});
}
//按钮动作 ,列出文件夹里面得文件,并显示相关文件类型//////////////////////////////////
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == exitItem) {
int exitChoose = JOptionPane.showConfirmDialog(this, "确定要退出么?", "退出提示", JOptionPane.OK_CANCEL_OPTION);

if (exitChoose == JOptionPane.OK_OPTION) {
System.exit(0);
} else {
return;
}
}
else if(e.getSource() == zuozhe)
{
JOptionPane.showMessageDialog(this, "文件管理器(JTree练习)", "关于", JOptionPane.OK_CANCEL_OPTION);
}
else if(e.getSource() == help)
{
JOptionPane.showMessageDialog(this, "右边文件列表双击打开文件夹\n暂时只支持打开.txt|.java|.htm和word文件", "提示", JOptionPane.OK_CANCEL_OPTION);
}
else if(e.getSource()==newfiles)
{
Object obj = jtree.getLastSelectedPathComponent();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) obj;
String name = node.getUserObject().toString();
newFolder(name+File.separator+"新建文件夹");
jtree.updateUI();
}
else if(e.getSource()==newfload)
{
newFolder(zhantie()+File.separator+"新建文件夹");
}
else if(e.getSource()==popupMenu_Delete)
{
Object obj = jtree.getLastSelectedPathComponent();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) obj;
String name = node.getUserObject().toString();
int exitChoose = JOptionPane.showConfirmDialog(this, "确定要删除么?", "提示", JOptionPane.OK_CANCEL_OPTION);
if (exitChoose == JOptionPane.OK_OPTION) {
delFolder(name);
} else {
return;
}
//        TreePath path = jtree.getSelectionPath();
//        FileNode node1 = (FileNode)path.getLastPathComponent();
//        ((DefaultTreeModel)jtree.getModel()).nodeStructureChanged(node1);
//DefaultTreeModel model = (DefaultTreeModel)jtree.getModel();
}
else if(e.getSource()==b_del)
{
int exitChoose = JOptionPane.showConfirmDialog(this, "确定要删除么?", "提示", JOptionPane.OK_CANCEL_OPTION);
if (exitChoose == JOptionPane.OK_OPTION)
{
if ((new File(zhantie()+File.separator+F_list.getSelectedValue())).isDirectory()) //测试是否是目录
{
delFolder(zhantie()+File.separator+F_list.getSelectedValue());
}

else
delFile(zhantie()+File.separator+F_list.getSelectedValue());
}
else
{
return;
}
// clearData();
}
else if(e.getSource()==b_copy||e.getSource()==popupMenu_Copy||e.getSource()==copy)

{
MainFrame frm = new MainFrame();
frm.setVisible(true);
}
else if(e.getSource()==b_rename)
{
renamest.setText(F_list.getSelectedValue().toString());
f.setVisible(true) ;// 让组件可见
}
else if(e.getSource()== sure)
{
newname=renamest.getText();

int exitChoose = JOptionPane.showConfirmDialog(this, "确定要改名么?", "提示", JOptionPane.OK_CANCEL_OPTION);
if (exitChoose == JOptionPane.OK_OPTION)
{
File oldff= new File(zhantie()+File.separator+F_list.getSelectedValue());
File newff= new File(zhantie()+File.separator+newname);
oldff.renameTo(newff);
f.setVisible(false);
}

else
{
return;
}
}
else if(e.getSource()==newfile||e.getSource()==newItem)
{
fd=new FileDialog(this,"新建文件",FileDialog.SAVE);
fd.setDirectory(zhantie());
fd.setVisible(true);

File f=new File(fd.getDirectory(),fd.getFile());
try{
FileOutputStream fos=new FileOutputStream(f);
fos.write("".getBytes());
fos.close();
}catch(Exception ecp){}
}
else if(e.getSource()==b_Zip||e.getSource()==p_zip)
{
zipname.setText("*.zip");

ff.setVisible(true) ;// 让组件可见   
}
else if(e.getSource()==ok)
{
String in;
newname=zipname.getText();
if(F_list.isSelectionEmpty())
in=zhantie();
else
in=zhantie()+File.separator+F_list.getSelectedValue();
ZIPUtil.CreateZipFile(in,zhantie()+File.separator+newname);

ff.setVisible(false);
}
else if(e.getSource()==b_open)
{
try
{
TreePath p=jtree.getLeadSelectionPath();
String text=F_list.getSelectedValue().toString();
Object []path= p.getPath();
String sr="";
for(int i=1;i <path.length;i++)
sr+=File.separator+path[i].toString();
sr=sr.substring(1);
File f = new File(sr+File.separator+text);
sr=sr.substring(1);
status.setText(f.toString());
if(f.isDirectory())
{
int index=jtree.getRowForPath(p);
jtree.expandRow(index); ///确保指定行中的节点展开,并且可查看
while (!(jtree.getLastSelectedPathComponent().toString().trim().equals(text)))
jtree.setSelectionRow(index++); ///选择显示的指定行的节点。
jtree.expandRow(index-1);

}
else
{
String postfix=text.toUpperCase();
if(postfix.indexOf(".TXT")!=-1||postfix.indexOf(".JAVA")!=-1||
postfix.indexOf(".HTM")!=-1||postfix.indexOf(".LOG")!=-1)
Runtime.getRuntime().exec("NotePad.exe "+sr+File.separator+text);
else if(postfix.indexOf(".DOC")!=-1)
{
Runtime.getRuntime().exec("c:\\Program Files\\Microsoft Office\\Office14\\WINWORD.EXE .\\"+sr+File.separator+text);

}
}
}
catch(Exception ee){}
}
}
/**
*  新建目录
*  @param  folderPath  String    c:/fqf
*  @return  boolean
*/
public  void  newFolder(String  folderPath)  {

try  {
String  filePath  =  folderPath;
filePath  =  filePath.toString();
  myFilePath  =  new  (filePath);
if  (!myFilePath.exists())  {
myFilePath.mkdir();
}
else
{
for(int i=1;;i++)
{
filePath  =  folderPath+" "+"("+i+")";

{
filePath  =  folderPath+" "+"("+i+")";
filePath  =  filePath.toString();
  myFilePathi  =  new  (filePath);
if(!myFilePathi.exists())
{
myFilePathi.mkdir();
break;
}
}
}
}
catch  (Exception  e)  {
System.out.println("新建目录操作出错");
e.printStackTrace();
}
}
/**
*  删除文件
*  @param  filePathAndName  String  文件路径及名称  如c:/fqf.txt
*  @param  fileContent  String
*  @return  boolean

*/
public  void  delFile(String  filePathAndName)  {
try  {
String  filePath  =  filePathAndName;
filePath  =  filePath.toString();
  myDelFile  =  new  (filePath);
myDelFile.delete();
}
catch  (Exception  e)  {
System.out.println("删除文件操作出错");
e.printStackTrace();
}
}
/**
*  删除文件夹
*  @param  filePathAndName  String  文件夹路径及名称  如c:/fqf
*  @param  fileContent  String
*  @return  boolean
*/
public  void  delFolder(String  folderPath)  {
try  {
delAllFile(folderPath);  //删除完里面所有内容
String  filePath  =  folderPath;
filePath  =  filePath.toString();
  myFilePath  =  new  (filePath);
myFilePath.delete();  //删除空文件夹
}
catch  (Exception  e)  {
System.out.println("删除文件夹操作出错");
e.printStackTrace();
}
}
/**
*  删除文件夹里面的所有文件
*  @param  path  String  文件夹路径    c:/fqf
*/
public  void  delAllFile(String  path)  {
File  file  =  new  File(path);
if  (!file.exists())  {
return;
}
if  (!file.isDirectory())  {
return;
}
String[]  tempList  =  file.list();
File  temp  =  null;
for  (int  i  =  0;  i  <  tempList.length;  i++)  {
if  (path.endsWith(File.separator))  {
temp  =  new  File(path  +  tempList[i]);
}
else  {
temp  =  new  File(path  +  File.separator  +  tempList[i]);
}
if  (temp.isFile())  {
temp.delete();
}
if  (temp.isDirectory())  {
delAllFile(path+"/"+  tempList[i]);//先删除文件夹里面的文件
delFolder(path+"/"+  tempList[i]);//再删除空文件夹
}
}
}
public String zhantie()////////////获得jtree节点路径

{
Object obj = jtree.getLastSelectedPathComponent();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) obj;
String name = node.getUserObject().toString();
return name;
}
public void renames(){
}
//左侧创建的树
private DefaultMutableTreeNode createTreeModel()
{
DefaultMutableTreeNode rootNode=new DefaultMutableTreeNode("我的电脑"); ///头节点rootNode
File[] rootPath = File.listRoots(); /////列出可用的文件系统根。
for(int i=0;i <rootPath.length;i++)
{
FileNode Node = new FileNode(rootPath[i]);
Node.Explore();
rootNode.add(Node);
}
return rootNode;
}
public static void main(String args[]) //////主函数
{
new scaner().setVisible(true);
}
/*
public void clearNodeData(DefaultMutableTreeNode parent) {
for (int i = 0; i < parent.getChildCount(); ++i) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) parent.getChildAt(i);
clearNodeData(node);


}
parent.removeAllChildren();
}
public void clearData() {
clearNodeData((DefaultMutableTreeNode) jtree.getModel().getRoot());
jtree.updateUI();
}
*/
class FileNode extends javax.swing.tree.DefaultMutableTreeNode ///文件节点类
{
/**

*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
private boolean explored = false;
public FileNode(File file)
{
setUserObject(file); ////将此节点的用户对象设置为 userObject
}
@Override
public boolean getAllowsChildren()
{
return isDirectory();
}
@Override
public boolean isLeaf()
{
return !isDirectory();
}
public File getFile()
{
return (File)getUserObject(); ////返回此节点的用户对象
}

public boolean isExplored()
{
return explored;
}
public boolean isDirectory()
{

return getFile().isDirectory(); ////测试此抽象路径名表示的文件是否是一个目录
}
@Override
public String toString()
{
File file = (File)getUserObject(); ////返回此节点的用户对象
String filename = file.toString(); ///文件名
int index = filename.lastIndexOf(File.separator); ////与系统有关的默认名称分隔符,为了方便,它被表示为一个字符串
return (index != -1 && index != filename.length()-1) ? filename.substring/*返回一个新的字符串,它是此字符串的一个子字符串。*/
(index+1) : filename;
}
public void Explore()
{

if(!isDirectory()) return;
if(!isExplored())
{
File file = getFile();
File[] children = file.listFiles(); /////返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。
for(int i=0; i < children.length; ++i)
{
File f=children[i];
if(f.isDirectory())add(new FileNode(children[i]));
}
explored = true;
}
}
}
class Clock extends Thread { // 模拟时钟
public void run() {
while (true) {
GregorianCalendar time = new GregorianCalendar();
int hour = time.get(Calendar.HOUR_OF_DAY);
int min = time.get(Calendar.MINUTE);
int second = time.get(Calendar.SECOND);
if(min<10)

{
shijian.setText("    当前时间:" + hour + ":0" + min + ":" + second);
}
else
shijian.setText("    当前时间:" + hour + ":" + min + ":" + second);
try {
Thread.sleep(950);
} catch (InterruptedException exception) {
}
}
}
}
}
//////////////// IOTest类////////////////////////////
import *;
import javax.swing.*;
public class IOTest
{
public static void copyFile(String in,String out)
{
File of=new File(in);
if(of.isFile())
{

FileInputStream fin = null;
FileOutputStream fout = null;
try
{
fin = new FileInputStream(new File(in));
fout = new FileOutputStream(new File(out));
byte[] b = new byte[512];
while(true)
{
if(fin.read(b)!=-1)
{
fout.write(b);

}
else
{
break;
}
}
System.out.println("成功将文件:" + in + "复制到:" + out);
JOptionPane.showMessageDialog(null, "文件已成功复制!");
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
fin.close();///释放
fout.close();
}catch(IOException ioe)

ioe.printStackTrace();
}
}
}
else
{
try  {
(new  File(out)).mkdirs();  //如果文件夹不存在  则建立新文件夹
File  a=new  File(in);
String[]  file=a.list();
File  temp=null;

for  (int  i  =  0;  i  <  file.length;  i++)
{
if(in.endsWith(File.separator))
{
temp=new  File(in+file[i]);
}
else
{
temp=new  File(in+File.separator+file[i]);
}
if(temp.isFile())
{

FileInputStream  input  =  new  FileInputStream(temp);
FileOutputStream  output  =  new  FileOutputStream(out  +  "/"  +
(temp.getName()).toString());
byte[]  b  =  new  byte[1024  *  5];
int  len;
while  (  (len  =  input.read(b))  !=  -1)
{
output.write(b,  0,  len);
}
output.flush();
output.close();
input.close();

}
if(temp.isDirectory())//如果是文件夹
{
copyFile(in+"/"+file[i],out+"/"+file[i]);
}
}         
JOptionPane.showMessageDialog(null, "文件已成功复制!");
}
catch  (Exception  e)
{
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();

}
}
}
///////////// ZIPUtil类/////////////////////////////////
import
import
import
import
import
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
import javax.swing.JOptionPane;
public class ZIPUtil {
public static void CreateZipFile(String filePath, String zipFilePath) {
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipFilePath);
zos = new ZipOutputStream(fos);
writeZipFile(new File(filePath), zos, "");
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (zos != null)
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fos != null)
fos.close();
JOptionPane.showMessageDialog(null, "文件已成功压缩!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void writeZipFile(File f, ZipOutputStream zos, String hiberarchy) {
if (f.exists()) {
if (f.isDirectory()) {
hiberarchy += f.getName() + "/";
File[] fif = f.listFiles();
for (int i = 0; i < fif.length; i++) {
writeZipFile(fif[i], zos, hiberarchy);
}
} else {
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
ZipEntry ze = new ZipEntry(hiberarchy + f.getName());
zos.putNextEntry(ze);
byte[] b = new byte[1024];
while (fis.read(b) != -1) {
zos.write(b);
b = new byte[1024];
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static ZIPUtil zu = null;
public static ZIPUtil getInstance() {
if (zu == null)
zu = new ZIPUtil();
return zu;
}
}
//////////////////////////////////////////////////////////////
搜索更多相关主题的帖子: add String new File public 
2020-12-28 19:26
快速回复:我是Java初学者,遇到swing的习题,敲完发现很多问题,求纠正
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.027790 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved