2013-10-10 2 views
0

저는 Java를 처음 사용하면서 분실했습니다. 내가 파일에서 읽은 INT 값의 합계를 계산하는 방법을 찾아야한다, 메소드 getTotalMinutes에Java BufferedReader readline은 파일의 값을 계산합니다.

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileReader; 

/** 
* 
* @author Darwish 
*/ 
public class M3UReader { 

    /** 
    * @param args the command line arguments 
    */ 

    public static boolean isValidHeader(String playList) 
    { 
     boolean returnValue = false; 
     BufferedReader br; 
     try 
     { 
      br = new BufferedReader(new FileReader(new File(playList))); 
      String s = br.readLine(); // declares the variable "s" 
      if(s.startsWith("#EXTM3U")) { // checks the line for this keyword 
       returnValue = true; // if its found, return true 
      } 
      br.close(); 
     } 
     catch (Exception e) 
     { 
      System.err.println("isValidHeader:: error with file "+ playList + ": " + e.getMessage()); 
     } 

     return returnValue; 
    } 
    public static int getNumberOfTracks(String playList) 
    { 
     int numberOfTracks = 0; // sets the default value to zero "0" 
     try 
     { 
      BufferedReader br = new BufferedReader(new FileReader(new File(playList))); 
      String s; 
      while((s = br.readLine())!=null) // if "s" first line is not null 
      { 
       if(s.startsWith("#")==false) { // if the first line starts with "#" equals to false. 
        numberOfTracks++; // increments 
       } 
      } 
      br.close(); 
     } 
     catch (Exception e) 
     { 
      numberOfTracks = -1; // chek if the file doesnt exist 
      System.err.println("could not open/read line from/close filename "+ playList); 
     } 
     return numberOfTracks; 

    } 

    public static int getTotalMinutes(String playList) 
    { 
     // code needed here 
    } 

    public static void main(String[] args) { 
     // TODO code application logic here 
     String filename = "files\\playlist.m3u"; // finds the file to read (filename <- variable declaration.) 
     boolean isHeaderValid = M3UReader.isValidHeader(filename); // declares the variabe isHeaderValid and links it with the class isValidHeader 
     System.out.println(filename + "header tested as "+ isHeaderValid); // outputs the results 

     if(isHeaderValid) 
     { 
      int numOfTracks = M3UReader.getNumberOfTracks(filename); 
      System.out.println(filename + " has "+ numOfTracks + " tracks "); 
     } 

    } 
} 

:

나는이 코드를 가지고있다. 이 파일의 데이터는 다음과 같습니다.

#EXTM3U 
#EXTINF:537,Banco De Gaia - Drippy F:\SortedMusic\Electronic\Banco De Gaia\Big Men Cry\01 Drippy.mp3 
#EXTINF:757,Banco De Gaia - Celestine F:\SortedMusic\Electronic\Banco De Gaia\Big Men Cry\02 Celestine.mp3 
#EXTINF:565,Banco De Gaia - Drunk As A Monk F:\SortedMusic\Electronic\Banco De Gaia\Big Men Cry\03 Drunk As A Monk.mp3 
#EXTINF:369,Banco De Gaia - Big Men Cry F:\SortedMusic\Electronic\Banco De Gaia\Big Men Cry\04 Big Men Cry.mp3 

#EXTINF : 다음의 숫자는 위의 데이터에서 오는 음악의 길이입니다 (초).

getTotalMinutes 메서드에 쓸 코드가 무엇인지 모르기 때문에 프로그램에서 파일의 분을 읽은 다음 모든 분을 계산하여 총 시간을 얻을 수 있습니다. 웹을 검색하여 불행하게도이 방법을 찾지 못했습니다. 그래서 어떤 도움을 주셔서 감사합니다.

+0

질문이 해결된다. 시도한 해결책, 실패한 이유 및 예상되는 결과를 포함시킵니다. –

+0

* "음악 길이"*는 무엇을 의미합니까? 분, 초, 틱, 퍽, 팀 탬 (tim-tams)? – MadProgrammer

+0

음악 길이는 초입니다. –

답변

0
당신이 사용할 수

, 그것 당신의 getNumberTracks 방법의 사본하지만 당신이 총 분하는 데 필요한 방법 파일을 구문 분석 : here에서 제공되는 설명에 따라 그래서

public static final String beginning = "#EXTINF:"; 
public static final String afterNumber = ","; 

public static int getTotalMinutes(String playList) { 
    int value = 0; 
    try { 
     BufferedReader br = new BufferedReader(new FileReader(new File(playList))); 
     String s; 
     while ((s = br.readLine()) != null) // if "s" first line is not null 
     { 
      if (s.contains(beginning)) { 
       String numberInString = s.substring(beginning.length(), s.indexOf(afterNumber)); 
       value += Integer.valueOf(numberInString); 
      } 
     } 
     br.close(); 
    } catch (Exception e) { 
    } 
    return value; 
} 
+0

와우, 내 문제를 해결해 주셔서 감사합니다! 이제 getTotalMinutes 메서드에 모든 것을 넣을 수있는 방법을 찾아야합니다. s.contains를 사용하려고 생각했지만() 안에 무엇을 넣을 지 모릅니다. 불행히도 % d을 (를) 사용하려했으나 작동하지 않았습니다. –

0

을, 숫자 value는 초 수입니다.

String text = "#EXTINF:537,Banco De Gaia - Drippy F:\\SortedMusic\\Electronic\\Banco De Gaia\\Big Men Cry\\01 Drippy.mp3"; 
String durationText = text.substring(text.indexOf(":") + 1, text.indexOf(",")); 
int durationSeconds = Integer.parseInt(durationText); 
System.out.println(durationSeconds); 

537을 인쇄 할 #EXTINF:{d},{t}의 형식으로 String 당신이 값을 얻기 위해 간단한 String 조작을 사용할 수 있어야 주어진 그래서

, ...

다음 우리는 단지 간단한 시간 계산을 할 필요가 있습니다 ...

double seconds = durationSeconds; 
int hours = (int)(seconds/(60 * 60)); 
seconds = seconds % (60 * 60); 
int minutes = (int)(seconds/60); 
seconds = seconds % (60); 

System.out.println(hours + ":" + minutes + ":" + NumberFormat.getNumberInstance().format(seconds)); 

어느 것이 0:8:57 (또는 8 분 57 초)

+0

입력 해 주셔서 감사합니다. 나는 user2854908의 코드를 사용하여 초를 몇 분 안에 얻을 수 있었다 : int numOfMinutes = M3UReader.getTotalMinutes (filename); System.out.println (파일 이름 + ""numOfMinutes/60) + "분"+ "numOfTracks +"트랙이 있습니다. –

0

M3U 파일을 읽으려면 M3U 파서에 대한 정보를 검색해야합니다. 사용 가능한 효율적인 오픈 소스 파서가 이미 많이 있지만, 판매 또는 배포를 계획하고 있다면 라이센스에 세심한주의를 기울여야합니다.

M3u 파서는 빠르고 효율적인 것을 원한다면 유망한 것처럼 보입니다. 문제의 최소한의 이해를 증명해야하는 코드를 요청

M3u Parser

0
public static int getTotalMinutes(String filename) { 
    int totalSeconds = 0; 

    if (isValidHeader(filename)) { 
     try (BufferedReader br = new BufferedReader(new FileReader(new File(filename)));) { 
      String nextLine; 
      while ((nextLine = br.readLine()) != null) { 
       //If the next line is metadata it should be possible to extract the length of the song 
       if (nextLine.startsWith(M3U_METADATA)) { 
        int i1 = nextLine.indexOf(":"); 
        int i2 = nextLine.indexOf(","); 
        String substr = nextLine.substring(i1 + 1, i2); 
        totalSeconds += Integer.parseInt(substr); 
       } 
      } 
     } catch (IOException | NumberFormatException e) { 
      //Exception caught - set totalSeconds to 0 
      System.err.println("getTotalSeconds:: error with file " + filename + ": " + e.getMessage()); 
      totalSeconds = 0; 
     } 
    } 

    return totalSeconds; 
}