2011-03-12 25 views
1

我希望有人看看下面的代碼,並告訴我是否有任何明顯的錯誤/我正在做的奇怪的事情。我只是在尋找一般的編碼建議。如果你能指出我會朝着正確的方向發展,那將會很棒。Java編程指導

我對java很陌生。我寫了以下幾十次並重新編寫了它,並且它工作正常。我只想讓別人看看是否有什麼東西突然出現,顯然是錯誤的。

import net.contentobjects.jnotify.JNotify; 
import net.contentobjects.jnotify.JNotifyListener; 
import java.io.*; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.awt.Dimension; 
import java.awt.Toolkit; 
import java.awt.*; 
import javax.swing.JTextArea; 
import javax.swing.JFrame; 
import javax.swing.JScrollPane; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.*; 
import javax.swing.JLabel; 

public class FileWatcher implements ActionListener { 
    private JTextArea textArea = new JTextArea(); 
    private JScrollPane pane = new JScrollPane(textArea); 
    private Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
    private JFrame frame = new JFrame(); 
    private JButton startButton = new JButton("Clear"); 
    private JPanel panel = new JPanel(); 

    public FileWatcher(String path) { 
     Font font = new Font("Arial Unicode MS", Font.PLAIN, 13); 
     this.textArea.setEditable(false); 
     this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     this.pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); 
     this.frame.add(pane); 
     this.frame.setSize(500, 200); 
     this.frame.setLocation(screenSize.width - 500, screenSize.height - 250); 
     this.frame.setTitle("Monitoring: " + path + "..."); 

     this.textArea.setFont(font); 
     this.frame.add(panel, BorderLayout.SOUTH); 
     startButton.setPreferredSize(new Dimension(450, 20)); 
     this.panel.add(startButton); 
     this.startButton.addActionListener(this); 
     this.frame.setVisible(true);   
    } 

    private void sample(String path) throws Exception { 
     int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED 
       | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED; 
     boolean watchSubtree = true; 
     JNotify.addWatch(path, mask, watchSubtree, new Listener()); 
    } 

    public void actionPerformed(ActionEvent e) { 
     this.textArea.setText("");  
    } 

    public void TouchFile(String fName) { 
     if ((fName.indexOf("Thumbs") == -1) && (fName.indexOf(".rar") == -1) 
       && (fName.indexOf(".part") == -1)) { 
      String TodayDate = ""; 
      String fModifyDate = ""; 
      String line; 
      String line2 = "error"; 
      Calendar calendar = Calendar.getInstance(); 
      SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); 
      File filename = new File(fName); 
      try { 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      TodayDate = dateFormat.format(calendar.getTime()); 
      fModifyDate = dateFormat.format(filename.lastModified()); 
      try { 
       Thread.currentThread().sleep(1000); 

       while ((line2.indexOf("error") != -1) 
         && (!fModifyDate.equals(TodayDate))) { 
        line2 = " "; 
        line = " "; 
//     Process p = 
//     Runtime.getRuntime().exec("C:\\Users\\BLUE\\Documents\\MYDROP~1\\Utils\\WatchFolder\\touch.exe " 
//     + "\"" + fName + "\""); 
        Process p = Runtime.getRuntime().exec("touch.exe " + "\"" + fName + "\""); 
        BufferedReader input = new BufferedReader(
          new InputStreamReader(p.getInputStream())); 
        while ((line = input.readLine()) != null) { 
         line2 = line2 + line; 
         showInfo(line); 
        } 
        input.close(); 
        p.waitFor(); 
       } 
      } catch (Exception err) { 
       err.printStackTrace(); 
      } 
     } 
    } 

    String chopData(String data) { 
     File file = new File(data); 
     String fileName= file.getName(); 
     if (data.indexOf("Touched") != -1) { 
      int tIndex = data.indexOf("Touched"); 
      data = data.substring(0,tIndex+8) + "..." + fileName; 
     } 

     if ((data.indexOf("Touched") == -1) && (data.length() > 70)) { 
      data = data.substring(0, data.indexOf(" ")) + " ... " 
        + data.substring(data.length() - 55); 
     } 
     return data; 
    } 

    public void showInfo(String data) { 
     data = chopData(data); 
     this.textArea.append(data + "\n"); 
     this.frame.getContentPane().validate(); 
     this.textArea.setCaretPosition(this.textArea.getText().length()); 
    } 

    class Listener implements JNotifyListener { 
     public void fileRenamed(int wd, String rootPath, String oldName, String newName) { 
      showInfo("renamed ..." + oldName.substring(oldName.length() - 25) 
        + " -> ..." + newName.substring(newName.length() - 25)); 
     } 

     public void fileModified(int wd, String rootPath, String name) { 
      TouchFile(rootPath + "\\" + name); 
     } 

     public void fileDeleted(int wd, String rootPath, String name) { 
      showInfo("deleted " + name); 
     } 

     public void fileCreated(int wd, String rootPath, String name) { 
      TouchFile(rootPath + "\\" + name); 
      showInfo("created " + name); 
     } 

     void print(String msg) { 
      showInfo(msg); 
     } 
    } 

    public static void main(String[] args) { 

     try { 
      if (args.length > 0) { 
       FileWatcher[] fwArray = new FileWatcher[args.length]; 
       for (int i = 0; i < args.length; i++) { 
        fwArray[i] = new FileWatcher(args[i]); 
        fwArray[i].sample(args[i]); 
       } 

      } else { 
       FileWatcher watcher = new FileWatcher("H:\\download"); 
       watcher.sample("H:\\download"); 

      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 


} 

回答

3

塊等

try { 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

硬編碼路徑

FileWatcher("H:\\download"); 

幻數

if ((data.indexOf("Touched") == -1) && (data.length() > 70)) { 
     data = data.substring(0, data.indexOf(" ")) + " ... " 
       + data.substring(data.length() - 55); 

未優化進口

import javax.swing.*; 
import javax.swing.JLabel; 
+0

謝謝!那些人擡頭看了一下,但我現在已經明白了。謝謝你的幫助。 – zincc 2011-03-13 13:11:06

2
public void TouchFile(String fName) 

方法名稱錯誤。你不應該大寫第一個字符。

TodayDate = dateFormat.format(calendar.getTime()); 

Varialbe名稱是錯誤的。你不應該大寫第一個字符。

編寫代碼時一致性非常重要。遵循標準慣例。

+0

謝謝!我很sl。。 – zincc 2011-03-13 13:11:48

1

Thread.currentThread().sleep(1000);

應該

Thread.sleep(1000);

!fName.contains("Thumbs")

,而不是

fName.indexOf("Thumbs") == -1

+0

謝謝!我認爲必須有一個更好的方法來做到這一點。 – zincc 2011-03-13 08:34:32

1

創造更多的CLA sses - 第一類 - 介紹,第二類I/O操作。移動內部類單獨的文件,創建包TouchFile簡單

製作方法 - 拆分它更小的部分,改變名稱touchFile

刪除註釋代碼,幻數,創建最終的字符串與路徑(「H:\下載「)和文本

我認爲這種情況是不是你所期望的:

if ((fName.indexOf("Thumbs") == -1) && (fName.indexOf(".rar") == -1) 
    && (fName.indexOf(".part") == -1)) 

更好的辦法:

fName.toLowerCase().endsWith(".rar") ... 
+0

嘿!謝謝你們。這是比我預期得到的更多反饋和建議。 – zincc 2011-03-12 18:21:09

2

HI Zincc,歡迎來到StackExchange並歡迎來到java。

堆棧交換在測試特定的網站現在對於這樣的問題,你可能想看一看:https://codereview.stackexchange.com/

此外,我會建議使用完全合格的類名來使用import語句:

import java.awt.Toolkit; 

,而不是像:

import java.awt.*; 

,因爲它會使編譯過程需要多一點的時間,不是一個真正的大問題,但你可能要閱讀這篇文章:Java Performance Tuning

關心! Jhurtado

+0

哇,感謝codereviw網址 - 我以前不知道這個網站 - 看起來很棒 – smas 2011-03-12 18:29:01

+0

是的!它處於Beta狀態,所以如果你們喜歡它,請加入並參與! :) – jhurtado 2011-03-12 18:33:15

+0

感謝您的鏈接和建議! :) – zincc 2011-03-12 18:39:53

1

變量範圍。變量應該被聲明爲正確的地方,它們不是全部用在一大堆C++風格的頂部。在chopData()中,文件名僅用於其中一個ifs。在touchFile這些變量中的大部分應該在try {}中作用域,因爲你沒有在catch中引用它們。

一般捕捉類型異常不是一個好主意。它可能導致一些相當奇怪的行爲,儘管它在這裏可能有意義。捕獲您知道可以處理的異常,讓其他泡泡進入運行時。

我也會考慮將其重構爲幾個類。考慮使用MVC-esque模式來解耦代碼,它定義了面板的外觀以及它如何響應用戶/文件系統事件。

+0

謝謝!那些都很棒。不得不查看MVC,這正是我在思考的內容。我想以某種明智的方式劃分代碼,但不知道最好的方法是什麼。謝謝! – zincc 2011-03-13 13:21:07