Welcome to HBH! If you had an account on hellboundhacker.org you will need to reset your password using the Lost Password system before you will be able to login.

FileTool - Java Code Bank


FileTool
This was a project I started on quite a while ago in order to make editing work in the shell environment that I work in at school easier through a graphical environment. Now, granted, this is nowhere near done, and I do have a lot of work left to do on it, I think that so far, I've done a pretty good job. But I'd like to know what you think.
                import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.awt.*;

class Window extends JFrame {
	public Window(String title) {
		super(title);
		setSize(600,300);
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	public void init() {
		setVisible(true);
	}
}

public class FileTool {
	private static JList files;
	private static Vector path;
	private static Window win;
	private static String curr;
	private static MouseListener mouseListener;
	private static Key kl;
	private static JScrollPane pane;
	private static String sep;
	private static JFrame editor;
	private static JScrollPane document;
	private static JTextArea jta;
	private static JPanel menubar;
	private static JMenuBar menu;
	private static JMenu file;
	private static JMenuItem save;
	private static JMenuItem se;
	private static JMenuItem exit;
	private static JMenuItem saveas;
	private static String cf;
	private static JCheckBox useDefault;
	private static JPanel defaultPane;
	private static JTextField Default;
	private static CheckListener cl;
	private static JFileChooser fc;
	private static MenuListener ml;
	
	private static void save() {
		//lolwut save that file?
		FileOutputStream out;
		PrintStream p;
		try {
             out = new FileOutputStream(cf);
			 p = new PrintStream( out );
			 p.println (jta.getText());
             p.close();
        } 
        catch (Exception e)
        {
                 JOptionPane.showMessageDialog(null,"Error writing to file");
		}
		//okay, we saved, the file is fine.
		System.out.println("File "+cf+" saved.");				
		
	}
	
	public static Vector getListing(String dir) {
		Vector vec = new Vector();
		File f = new File(dir);
		int i = 0;		
		if(path.size() > 1 ) { vec.add("Go Up One Directory"); }
		File [] g = f.listFiles();
		Arrays.sort(g);
		for(File x : g) {
			if(x.isDirectory()) {
				vec.add(x.getName()+sep);
			} else {
				vec.add(x.getName());
			}
		}
		return vec;
	}
	private static String getPath() {
		String ret = "";
		String x = "";
		for(int i = 0; i < path.size(); i++) {
			x = (String)path.get(i);
			ret += x + sep;
		}
		return ret.replace("\\\\","\\");
	}	
	public static class MenuListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			JMenuItem source = (JMenuItem)e.getSource();
			doAction(source);
		}
	}
	public static void doAction(Component source) {
		if(source == save) {					
				//save that file, yoda!
				save();
		} else if(source == se) {					
				//save that file, then exit!
				save();
				editor.setVisible(false);
		} else if(source == exit) {									
				//run away!
				editor.setVisible(false);
		} else if(source == saveas) {								
			int returnVal = fc.showOpenDialog(null);
			if(returnVal == JFileChooser.APPROVE_OPTION) {
				cf = fc.getSelectedFile().getName();
			}
			save();				
		} else {				
				JOptionPane.showMessageDialog(null,"Cest ne pas un hack!");
				//c'est ne pas un hack!
				return;
		}
	}
	
	public static void operate(String item) {
		String stuff = new String("");		
		String test = item;
		if(item.equals("Go Up One Directory")) { test = ".."; }
		File t = new File(getPath()+test);
		if(t.isDirectory()) {			
			if(item.equals("Go Up One Directory")) {				
				path.remove(path.size()-1);
			} else {
				path.add(test);
			}				
			String g = getPath();
			Vector v = getListing(g);
			changeList(v);			
		} else {
			if(!useDefault.isSelected()) {
				useDefaultEditor(test);
			} else {
				try {
					Runtime.getRuntime().exec(Default.getText()+" "+getPath()+test);
				} catch(Exception e) {
					JOptionPane.showMessageDialog(null,"Could not find: "+Default.getText()+". Reverting to default editor.");
					useDefaultEditor(test);
				}
			}	
		}
	}
	private static String readFile(String item) throws Exception {
			int rows = 1;
			int cols = 1;
			String stuff = "";
			String buf = "";
			FileInputStream fstream = new FileInputStream(getPath()+item);
			DataInputStream in = new DataInputStream(fstream);
			while (in.available() !=0) {
				buf = in.readLine() + '\n';
				rows++;
				cols = (buf.length()>cols?buf.length():cols);
				stuff += buf;
			}
			jta.setRows(rows);
			jta.setColumns(cols+5);
			in.close();
			return stuff;
	}
	private static void useDefaultEditor(String item) {	
		try {											
			jta.setText(readFile(item));
			jta.setSelectionStart(0);
			jta.setSelectionEnd(0);
			jta.moveCaretPosition(0);
			cf = getPath()+item;
			editor.setVisible(true);
			} 
			catch (Exception e)
			{
				System.err.println("File input error");
			}
	}
	public static void main(String[] args) {
		useDefault = new JCheckBox("Use different editor: ");
		useDefault.setToolTipText("Check this and change the field to the right to use an editor on your system (i.e., notepad in windows, and vim in linux.) If you don't check it, you will use the editor built into this program.");
		useDefault.addMouseListener(new CheckListener());
		
		Default = new JTextField(50);
		Default.setEditable(false);		
		
		fc = new JFileChooser();
		
		defaultPane = new JPanel();
		defaultPane.setLayout(new FlowLayout(FlowLayout.LEFT));
		defaultPane.add(useDefault);
		defaultPane.add(Default);
		defaultPane.setSize(600,50);
		
		win = new Window(curr);
		
		jta = new JTextArea(100,50);		
		
		editor = new JFrame("File Editor");
		editor.setSize(600,300);
		editor.setResizable(false);
		editor.addWindowListener(new WinL());
		
		ml = new MenuListener();
		
		menubar = new JPanel();
		menubar.setLayout(new FlowLayout(FlowLayout.LEFT));
		menubar.setSize(600,10);
		
		menu = new JMenuBar();
		menu.setSize(600,10);
		menu.setLayout(new FlowLayout(FlowLayout.LEFT));
		
		file = new JMenu("File");
		file.setMnemonic('F');
		
		save = new JMenuItem("Save");
		save.setMnemonic('S');
		save.setAccelerator(KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit(  ).getMenuShortcutKeyMask(  ), false));
		save.addActionListener(ml);
		file.add(save);
		
		se = new JMenuItem("Save And Exit");
		se.setMnemonic('E');
		se.setAccelerator(KeyStroke.getKeyStroke('E', Toolkit.getDefaultToolkit(  ).getMenuShortcutKeyMask(  ), false));
		se.addActionListener(ml);
		file.add(se);		
		
		saveas = new JMenuItem("Save As");
		saveas.setMnemonic('A');
		saveas.addActionListener(ml);
		file.add(saveas);
		
		exit = new JMenuItem("Exit");
		exit.setMnemonic('X');
		exit.setAccelerator(KeyStroke.getKeyStroke('W', Toolkit.getDefaultToolkit(  ).getMenuShortcutKeyMask(  ), false));
		exit.addActionListener(ml);
		file.add(exit);
		
		menu.add(file);
		
		menubar.add(menu);
			
		sep = new String(File.separator);
		path = new Vector();
		
		kl = new Key();
		
		document = new JScrollPane(jta);
		
		mouseListener = new MouseAdapter() {
		public void mouseClicked(MouseEvent e) {
		         if (e.getClickCount() == 2) {
		            JList source = (JList)e.getSource();
		            int index = source.locationToIndex(e.getPoint());
					String item = source.getSelectedValue().toString();
		            System.out.println("Double clicked on Item " + index + "("+item+")");
					operate(item);
		          }
		 }
		 };
		 
		File f = new File(".");
		curr = f.getAbsolutePath().substring(0,f.getAbsolutePath().length()-1);
		for(String x : curr.split((sep.equals("\\")?"\\\\":"/"),0)) {
			path.add(x);
		}	
				
		Vector vec = getListing(".");
		
		files = new JList(vec);
		files.addMouseListener(mouseListener);
		files.addKeyListener(kl);
		
		pane = new JScrollPane(files);
		pane.setSize(600,250);
		
		editor.add(menubar, BorderLayout.PAGE_START);
		editor.add(document);		
		
		win.add(pane, BorderLayout.PAGE_START);
		win.add(defaultPane);
		win.setTitle(curr);
		win.init();
	}
	private static void changeList(Vector v) {
		win.remove(pane);
		win.setVisible(false);
		win = new Window(getPath());
		files = new JList(v);
		files.addMouseListener(mouseListener);
		files.addKeyListener(kl);
		pane = new JScrollPane(files);
		win.add(pane, BorderLayout.PAGE_START);
		win.add(defaultPane);
		win.init();
	}
	
	private static class Key extends KeyAdapter {
		public void keyPressed(KeyEvent e) {
			JList source = (JList)e.getSource();
			if(e.getKeyCode() == KeyEvent.VK_ENTER) {
				operate(((JList)e.getSource()).getSelectedValue().toString());
			}
		}
	}
	private static class WinL extends WindowAdapter {
		public void windowClosing(WindowEvent e) {
			try {
				if(!(jta.getText().equals(readFile(cf)))) {
					int b = JOptionPane.showConfirmDialog(null,"Are you sure you would like to exit without saving?","Leaving so soon?",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
					if(b==JOptionPane.YES_OPTION) {
						((JFrame)e.getSource()).setVisible(false);
					}
					} else {
						((JFrame)e.getSource()).setVisible(false);
					}
			} catch(Exception ff) {
			}
		}
		public void windowClosed(WindowEvent e) {
			try {
				if(!(jta.getText().equals(readFile(cf)))) {
					int b = JOptionPane.showConfirmDialog(null,"Are you sure you would like to exit without saving?","Leaving so soon?",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
					if(b==JOptionPane.YES_OPTION) {
						((JFrame)e.getSource()).setVisible(false);
					}
					} else {
						((JFrame)e.getSource()).setVisible(false);
					}
			} catch(Exception ff) {
			}
		}
	}
	private static class CheckListener extends MouseAdapter {
		public void mouseClicked(MouseEvent e) {			
				Default.setEditable(!Default.isEditable());
		}
	}
}
            
Comments
Sorry but there are no comments to display