【问题标题】:Java BufferedReader readline calculate values from fileJava BufferedReader readline 从文件中计算值
【发布时间】:2013-10-10 03:05:58
【问题描述】:

我是 Java 新手,现在迷路了。

我有这个代码:

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 ");
        }

    }
}

在 getTotalMinutes 方法上,我必须找到一种方法来计算从文件中读取的 int 值的总数。该文件有以下数据:

#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 方法上写什么代码来让程序从文件中读取分钟数,然后计算所有分钟数以获得总分钟数。我在网上搜索了如何做到这一点,不幸的是我找不到任何东西。因此,我们将不胜感激。

【问题讨论】:

  • 要求代码的问题必须表明对所解决问题的最低理解。包括尝试过的解决方案、它们为什么不起作用以及预期的结果。
  • “音乐长度”是什么意思?分、秒、滴答声、滴答声、tim-tams?
  • 音乐的长度以秒为单位。

标签: java bufferedreader readline filereader


【解决方案1】:

您可以使用它,它只是您的 getNumberTracks 方法的副本,但它会以您需要获取总分钟数的方式解析文件:

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;
}

【讨论】:

  • 哇,这解决了我的问题,谢谢!现在我需要找到一种方法将所有内容放入 getTotalMinutes 方法中:) 我曾想过使用 s.contains,但我不知道在 () 中放入什么。我尝试使用 %d 不幸的是它没有用。
【解决方案2】:

所以,根据here提供的描述,数值是秒数。

因此,给定String 格式为#EXTINF:{d},{t},您应该能够使用简单的String 操作来获取值...

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...

接下来我们只需要做一些简单的时间算术...

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 秒)

【讨论】:

  • 感谢您的意见。在 user2854908 的代码的帮助下,我设法将秒变为分钟: int numOfMinutes = M3UReader.getTotalMinutes(filename); System.out.println(filename + " 有 "+ numOfTracks + " 个轨道," + (numOfMinutes/60) + " 总分钟数");
【解决方案3】:

要阅读 M3U 文件,您需要搜索有关 M3U 解析器的信息。已经有许多高效的开源解析器可用,但如果您打算出售或分发这些解析器,则需要密切关注它们的许可证。

如果您只是想要快速高效的东西,M3u Parser 看起来很有前途。

M3u Parser

【讨论】:

    【解决方案4】:
        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;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-07
      • 2019-01-30
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      • 2013-03-09
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多