2016-09-26 3 views
-2
  • У меня есть несколько файлов, сохраненных в моем локальном каталоге. Один видеофайл и один файл xml. Сведения о файле видео будут храниться в XML-файле.Java File Iteration in For loop

    • Мы перемещаем видеоролики из одной системы в другую. До
      Загрузка видеофайла и xml-данных из одной системы в другую
      системы, необходимо проверить название видео в другой системе и загрузить, только если одно и то же название не существует.

    • Это прекрасно работает. Но загрузка происходит 4 раза вместо 2 раз. Пожалуйста помоги.

Вот основной код:

List<File> videoFiles = new ArrayList<File>(); 
     List<File> xmlFiles = new ArrayList<File>(); 
File[] allVideos = checkVideos(); 
     for(File file:allVideos) { 
      if(file.getName().endsWith("flv")) { 
       videoFiles .add(file); 
      } 
      if(file.getName().endsWith("xml")) { 
       xmlFiles .add(file); 
      } 
     } 

     System.out.println(videoFiles.size()); 
     System.out.println(xmlFiles.size()); 

     processUpload(videoFiles ,xmlFiles); 

Вот методы:

private static void processUpload(List<File> videoFiles, List<File> xmlFiles) throws ParserConfigurationException, SAXException, IOException, ApiException { 
    NodeList nodes = null; 
    File video= null; 
    File xml = null; 
    String title = null; 
    String localFileTitle = null; 
    Media newMedia = null; 
    for(int i=0;i < videoFiles.size();i++) { 
     System.out.println("videoFiles.getName() ->"+videoFiles.get(i).getName()); 
     video= videoFiles.get(i); 
     for(int j=0;j < xmlFiles.size();j++) { 
      xml = xmlFiles.get(j); 
      System.out.println("xmlFiles.getName() ->"+xmlFiles.get(i).getName()); 
       nodes = parseXml(xml); 
       localFileTitle = processNodes(nodes); 
       title = checkTitles(localFileTitle); 
       newMedia = initiateUploadProcess(flv, title); 
       } 
      } 
     } 

private static NodeList parseXml(File xmlFile) throws ParserConfigurationException, SAXException, IOException { 
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
    Document doc = dBuilder.parse(xmlFile); 
    doc.getDocumentElement().normalize(); 
    //System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); 
    NodeList nList = doc.getElementsByTagName("video"); 
    return nList; 
} 

private static String processNodes(NodeList nodes) { 
String fileTitle = null; 
    if(nodes.getLength() >= 1) { 
     for (int temp = 0; temp < nodes.getLength(); temp++) { 
      Node nNode = nodes.item(temp); 
      if (nNode.getNodeType() == Node.ELEMENT_NODE) { 
       Element eElement = (Element) nNode; 
       fileTitle = eElement.getElementsByTagName("title").item(0).getTextContent(); 
       if(fileTitle != null) { 
       //System.out.println("Local File Title ------>"+fileTitle); 
       } 
      } 
     } 
    } 
    return fileTitle; 
} 

private static String checkTitles(String localTitle) throws ApiException { 
    String title = null; 
    MediaList mediaResponse = fetchVideos(caID); 
    if(mediaResponse.totalCount >= 1) { 
     for(MediaEntry media:mediaResponse.objects) { 
      if(!localTitle.equals(media.name)) { 
       System.out.println("Titles are not same. Need to return"); 
       title = localTitle; 
       } 
      } 
     } 
    return title ; 
} 

private static MediaEntry initiateUploadProcess(File videoFile, 
     String localFileTitle) throws ApiException, ParserConfigurationException, SAXException, IOException { 
    UploadToken ktoken = null; 
    UploadMedia entry = null; 
    MediaEntry mediaEntry = null; 
    ktoken = generateToken(); 
    if (ktoken != null) { 
     //System.out.println("ktoken.id ----------->" + ktoken.id); 
     if (ktoken.id != null) { 
      uploadToken(ktoken.id, flvFile); 
      entry = uploadMediaToChannel(categoryID, categoryName, localFileTitle); 
      if (entry.id != null) { 
       System.out.println("entry.id ------->" + entry.id); 
       mediaEntry = addMediaContent(ktoken.id, entry.id); 
       } 
      } 
     } 
    return mediaEntry; 
} 

Вот выход:

videoFiles.getName() ->22701846_91167469.flv 
xmlFiles.getName() ->22701846_91167469.xml 
Titles are not same. Need to return 
Titles are not same. Need to return 
video.id ------->0_50wh1m4p 
xmlFiles.getName() ->22701846_91167469.xml 
Titles are not same. Need to return 
Titles are not same. Need to return 
video.id ------->0_79v605ue 
videoFiles.getName() ->22701846_91477939.flv 
xmlFiles.getName() ->22701846_91477939.xml 
Titles are not same. Need to return 
Titles are not same. Need to return 
video.id ------->0_0kihent1 
xmlFiles.getName() ->22701846_91477939.xml 
Titles are not same. Need to return 
Titles are not same. Need to return 
Titles are not same. Need to return 
video.id ------->0_miogft0i 
+0

Это 2016. Почему бы вам не использовать новый файл API? – fge

ответ

0

В пс eudo-код, у вас есть что-то вроде этих двух петель там:

for (i in 1,2) 
    for (j in 1, 2) 
    ... 
    upload 

И вы удивитесь, что у вас есть 4 (2 х 2) загрузка?

Try что-то вроде:

for (i in 1,2) 
... fetch video file info 
... fetch xml file info 
upload 

вместо этого!

0

Выполнение вложенных циклов не очень эффективно, но я думаю, что проблема заключается в методе checkVideos() (не указан в вопросе), и он возвращает повторяющиеся файловые объекты.

Edit: линия, где вы печатаете файл XML использует «Я» переменной (от внешнего контура)

+0

Нет. Я напечатал и вижу только 4 файла в этой папке. 2 видео и 2 файла xml. – Sakuntala