---
title: "线程错误，高手帮忙，万分感激！！！在线等待。。。。。"
author: "damingchen_gd"
date: "2010-09-13T14:48:16Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-09-13T14:48:16Z"
id: 762059
url: "https://damingchen-gd.iteye.com/blog/762059"
---

实现一个定时自动上传文件到FTP的功能，但是线程报错。

TimeTask.java

\------------------------------------------------------------

import java.util.TimerTask;

public class TimeTask extends TimerTask {  
 ftpClient ftpclient = new ftpClient();  
 @Override  
 public void run() {  
  ftpClient.ScanFile();  
  System.out.println("Start Ftp Task");    
 }

}  
\-------------------------------------------------------------

 

ExecuteTask.java

\-------------------------------------------------------------

import java.util.Timer;

public class ExecuteTask {  
 static Parse parse;  
 int iTime;  
 /*  
  * Execute Task  
  \*/   
 public void Task() {  
  parse = new Parse();  
  try {  
   parse.viewXML("beanConfig.xml");  
   iTime = Integer.parseInt(parse.getSScanTime());  
   System.out.println(toString(iTime));  
  } catch (Exception e) {  
   // TODO Auto-generated catch block  
   e.printStackTrace();  
  }  
  Timer timer = new Timer();  
  timer.schedule(new TimeTask(), iTime * 1000,iTime * 1000);  
 }  
 private char\[] toString(int iTime2) {  
  // TODO Auto-generated method stub  
  return null;  
 }

   
}  
\----------------------------------------------------------------------

FileViewer.java

\----------------------------------------------------------------------

import java.io.\*;  
import java.util.ArrayList;  
import java.util.List;

/\**  
\* 讀取目錄及子目錄下指定檔案名的路徑 並放到一個陣列裡面返回遍歷  
\* @author  
\*  
\*/  
public class FileViewer {  
 private static List&lt;String&gt; fileList = new ArrayList&lt;String&gt;();  
   
 public static List&lt;String&gt; getFileList() {  
  return fileList;  
 }   
 /\**  
 *  
 * @param path 檔路徑  
 * @param suffix 尾碼名  
 * @param isdepth 是否遍歷子目錄  
 * @return  
 \*/  
 public static List&lt;String&gt; getListFiles(String path, String suffix, boolean isdepth)  
 {  
    File file = new File(path);  
    return FileViewer.listFile(file ,suffix, isdepth);  
 }  
   
 public static List&lt;String&gt; listFile(File f, String suffix, boolean isdepth)  
 {  
    //是目錄，同時需要遍歷子目錄  
    if (f.isDirectory() && isdepth == true)  
    {  
      File\[] t = f.listFiles();  
      for (int i = 0; i &lt; t.length; i++)  
      {  
       listFile(t\[i], suffix, isdepth);  
      }  
    }  
    else  
    {  
     String filePath = f.getAbsolutePath();  
     
     if(!suffix.equals("java") && !suffix.equals("JAVA")){  
      return null;  
     }  
     if(suffix != null)  
      {  
       //最後一個.(即尾碼名前面的.)的索引  
       int begIndex = filePath.lastIndexOf(".");  
       String tempsuffix = "";  
        
       if(begIndex != -1)//防止是檔但卻沒有尾碼名結束的檔  
       {  
        tempsuffix = filePath.substring(begIndex + 1, filePath.length());  
       }  
        
       if(tempsuffix.equals(suffix))  
       {  
        fileList.add(filePath);  
       }  
      }  
      else  
      {  
       //尾碼名為null則為所有檔  
       fileList.add(filePath);  
      }  
     
    }    
    return fileList;  
 }  
   
 /\**  
  * 刪除指定的檔  
  * @param fileName 全路徑檔案名  
  * @param newPath 新路徑  
  \*/  
 public static void deleteFile(String fileName,String newPath){  
  File file = new File(fileName);  
  //1.copy filename to success Directory  
  //2.delete filename  
  if (file.exists()){  
   copyFile(fileName,newPath);  
   file.delete();  
  }  
 }  
   
 /\**  
    * 複製單個文件  
    * @param oldPath String eg. c:/fqf.txt  
    * @param newPath String eg. f:/fqf.txt  
    * @return boolean  
    \*/  
 public static void copyFile(String oldPath, String newPath) {  
     try {  
       int bytesum = 0;  
       int byteread = 0;  
       File oldfile = new File(oldPath);  
       if (oldfile.exists()) { //File Exists  
         InputStream inStream = new FileInputStream(oldPath); //Load Old File  
         FileOutputStream fs = new FileOutputStream(newPath);  
         byte\[] buffer = new byte\[204800];  
         while ( (byteread = inStream.read(buffer)) != -1) {  
           bytesum += byteread; //File Size  
           //System.out.println(bytesum);  
           fs.write(buffer, 0, byteread);  
         }  
         inStream.close();  
       }  
     }  
     catch (Exception e) {  
       System.out.println("Copy File Error");  
       e.printStackTrace();

     }

 }

 /\**  
     * 方法追加檔：使用FileWriter  
     * @param fileName  
     * @param content  
     \*/  
 public static void appendMethod(String fileName, String content)  
 {  
     try  
     {  
      //打開一個寫檔器，構造函數中的第二個參數true表示以追加形式寫檔  
      FileWriter writer = new FileWriter(fileName, true);  
      writer.write(content + "\\r\\n");  
      writer.close();  
     }  
     catch (IOException e)  
     {  
      e.printStackTrace();  
     }  
 }

}  
\--------------------------------------------------------------------

ftpConnect.java

\--------------------------------------------------------------------

import java.io.FileInputStream;  
import java.io.IOException;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.StringTokenizer;

import sun.net.TelnetInputStream;  
import sun.net.TelnetOutputStream;  
import sun.net.ftp.FtpClient;

public class ftpClient {  
 static String PATH\_SYMBOL = "/";  
   
 static String userName = "admin";  //用戶名  
 static String passWord = "note";   //密碼  
 static FtpClient ftpClient;  
 static Parse parse;  
 static List&lt;String&gt; fileList = new ArrayList&lt;String&gt;();

 /\**  
  * FTP  
  \*/  
 public static void ftpConnect() {  
  try {  
   ftpClient = new FtpClient(parse.getIpAddress(),Integer.parseInt(parse.getPort()));  
   ftpClient.login(parse.getUsername(), parse.getPassword());

   System.out.println(ftpClient.welcomeMsg);

   ftpClient.binary();  
   String sFile;  
   String\[] sFileName;  
   for (int i = 0; i &lt; fileList.size(); i++) {  
    //  
    sFile = fileList.get(i);

    sFileName = sFile.split(PATH\_SYMBOL);  
    TelnetOutputStream ftpOut = ftpClient  
      .put(sFileName\[sFileName.length - 1]);  
    //  
    FileInputStream fs = new FileInputStream(sFile);  
    TelnetInputStream ftpIn = new TelnetInputStream(fs, true);  
    byte\[] buf = new byte\[204800];  
    int bufsize = 0;  
    while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {  
     ftpOut.write(buf, 0, bufsize);  
    }  
    ftpIn.close();  
    ftpOut.close();  
   }  
   System.out.println(ftpClient.getResponseString());

  } catch (IOException e) {  
   e.printStackTrace();  
  }  
  ftpClient.sendServer("QUIT\\r\\n");    
 }

 /\**  
  *  
  \*/  
 public static void LoadXML() {  
  parse = new Parse();  
  try {  
   parse.viewXML("beanConfig.xml");  
   System.out.println("scantime=" + parse.getSScanTime()  
     + ",filePath=" + parse.getSfilepath());  
  } catch (Exception e) {  
   e.printStackTrace();  
  }  
 }

 /\**  
  *  
  \*/  
 public static List&lt;String&gt; LoadFile() {  
  // fileViewer = new FileViewer();  
        // fileList = FileViewer.getListFiles(parse.getSfilepath(), "txt", true);  
  fileList = FileViewer.getListFiles(parse.getSfilepath(), "xls", true);  
  // out file  
  if (fileList == null) {  
   return null;  
  }  
  for (int i = 0; i &lt; fileList.size(); i++) {  
   System.out.println(fileList.get(i));  
  }  
  return fileList;  
 }

 /\**  
  *  
  \*/  
 public static void ScanFile() {  
  LoadXML();  
  if (LoadFile() == null) {  
   return;  
  }  
  ftpConnect();  
  String sFile;  
  String\[] sFileName;  
  for (int i = 0; i &lt; fileList.size(); i++) {  
   sFile = fileList.get(i);  
   sFileName = sFile.split(PATH\_SYMBOL);  
   FileViewer.deleteFile(fileList.get(i), parse.getSBackupfile()  
     + sFileName\[sFileName.length - 1]);  
  }  
  // fileList set clear;  
  fileList.clear();  
  // print Task End Info  
  System.out.println("Task End.");  
 }

 /\**  
  * @param args  
  \*/  
 public static void main(String\[] args) {  
  ExecuteTask excuteTask = new ExecuteTask();  
  excuteTask.Task();    
  // System.out.println(System.getProperty("os.name"));  
 }

 /\**  
  *  
  * @param pathList  
  *            String  
  * @throws Exception  
  \*/  
 public void buildList(String pathList) throws Exception {  
  ftpClient.ascii();  
  StringTokenizer s = new StringTokenizer(pathList, "/"); // sign  
  // int count = s.countTokens();  
  String pathName = "";  
  while (s.hasMoreElements()) {  
   pathName = pathName + "/" + (String) s.nextElement();  
   try {  
    ftpClient.sendServer("XMKD " + pathName + "\\r\\n");  
   } catch (Exception e) {  
    e = null;  
   }  
   // int reply = ftpClient.readServerResponse();  
  }  
  ftpClient.binary();  
 }

}

\--------------------------------------------------------------------

Parse.java

\--------------------------------------------------------------------

import java.io.File;

import javax.xml.parsers.DocumentBuilder;  
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;  
import org.w3c.dom.Element;  
import org.w3c.dom.Node;  
import org.w3c.dom.NodeList;

public class Parse {  
 private Document doc = null;  
 private String sScanTime;  
 private String sfilepath;  
 private String sBackupfile;  
 private String ipAddress;  
 private String port;  
 private String username;  
 private String password;

 public String getIpAddress() {  
  return ipAddress;  
 }

 public void setIpAddress(String ipAddress) {  
  this.ipAddress = ipAddress;  
 }

 public String getPort() {  
  return port;  
 }

 public void setPort(String port) {  
  this.port = port;  
 }

 public String getUsername() {  
  return username;  
 }

 public void setUsername(String username) {  
  this.username = username;  
 }

 public String getPassword() {  
  return password;  
 }

 public void setPassword(String password) {  
  this.password = password;  
 }

 public String getSBackupfile() {  
  return sBackupfile;  
 }

 public void setSBackupfile(String backupfile) {  
  sBackupfile = backupfile;  
 }

 public String getSScanTime() {  
  return sScanTime;  
 }

 public void setSScanTime(String scanTime) {  
  sScanTime = scanTime;  
 }

 public String getSfilepath() {  
  return sfilepath;  
 }

 public void setSfilepath(String sfilepath) {  
  this.sfilepath = sfilepath;  
 }

 public void init(String xmlFile) throws Exception {  
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
  DocumentBuilder db = dbf.newDocumentBuilder();  
  doc = db.parse(new File(xmlFile));  
 }

 public void viewXML(String xmlFile) throws Exception {  
  this.init(xmlFile);  
  Element element = doc.getDocumentElement();

  NodeList nodeList = doc.getElementsByTagName(element.getTagName());

  Node fatherNode = nodeList.item(0);

     NodeList childNodes = fatherNode.getChildNodes();  
  // System.out.println(childNodes.getLength());  
  for (int j = 0; j &lt; childNodes.getLength(); j++) {  
   Node childNode = childNodes.item(j);  
   if (childNode instanceof Element) {  
    if (childNode.getNodeName().equals("scantime")) {  
     this.setSScanTime(childNode.getFirstChild().getNodeValue());  
    } else if (childNode.getNodeName().equals("filepath")) {  
     this.setSfilepath(childNode.getFirstChild().getNodeValue());  
    } else if (childNode.getNodeName().equals("backupfile")) {  
     this.setSBackupfile(childNode.getFirstChild()  
       .getNodeValue());  
    } else if (childNode.getNodeName().equals("ipaddress")) {  
     this.setIpAddress(childNode.getFirstChild()  
       .getNodeValue());  
    } else if (childNode.getNodeName().equals("port")) {  
     this.setPort(childNode.getFirstChild()  
       .getNodeValue());  
    } else if (childNode.getNodeName().equals("username")) {  
     this.setUsername(childNode.getFirstChild()  
       .getNodeValue());  
    } else if (childNode.getNodeName().equals("password")) {  
      this.setPassword(childNode.getFirstChild()  
        .getNodeValue());  
    }  
   }  
  }  
 }  
}

\------------------------------------------------------------------------------

beanConfig.xml

\------------------------------------------------------------------------------

&lt;?xml version="1.0" encoding="UTF-8"?&gt;      
&lt;config&gt;    
 &lt;scantime&gt;1&lt;/scantime&gt;  
 &lt;filepath&gt;D:&lt;/filepath&gt;  
 &lt;backupfile&gt;/var/ftp/salse/&lt;/backupfile&gt;  
 &lt;ipaddress&gt;192.168.242.130&lt;/ipaddress&gt;  
 &lt;port&gt;21&lt;/port&gt;  
 &lt;username&gt;root&lt;/username&gt;  
 &lt;password&gt;mm520&lt;/password&gt;  
&lt;/config&gt;

\------------------------------------------------------------------------------

 

报错：

java.lang.NullPointerException  
 at java.io.Writer.write(Writer.java:110)  
 at java.io.PrintStream.write(PrintStream.java:453)  
 at java.io.PrintStream.print(PrintStream.java:603)  
 at java.io.PrintStream.println(PrintStream.java:742)  
 at ExecuteTask.Task(ExecuteTask.java:14)  
 at ftpClient.main(ftpClient.java:118)  
scantime=1,filePath=D:  
Exception in thread "Timer-0" java.lang.NullPointerException  
 at FileViewer.listFile(FileViewer.java:35)  
 at FileViewer.listFile(FileViewer.java:37)  
 at FileViewer.getListFiles(FileViewer.java:26)  
 at ftpClient.LoadFile(ftpClient.java:79)  
 at ftpClient.ScanFile(ftpClient.java:95)  
 at TimeTask.run(TimeTask.java:8)  
 at java.util.TimerThread.mainLoop(Timer.java:512)  
 at java.util.TimerThread.run(Timer.java:462)