0

我正在尝试使用 Scanner 类读取下面显示的简单文本文件,并设置了一个分隔符,scanner.useDelimiter(",");但是您可以看到每行末尾没有逗号,因此扫描仪不会读取每行的最后一个数字. 有人可以建议如何解决这个问题吗?

提前感谢您的帮助。

文本文件:

0,4,4,0,-4,2,2,8,16,20,20,12,8
1,6,7,1,-6,4,2,6,12,19,22,12,8
2,6,8,2,-7,5,2,4,11,19,23,14,8
3,4,8,4,-6,6,0,3,11,20,24,15,8
4,4,7,3,-5,5,0,0,12,20,24,16,10

这也是我的代码: public class ECGFilereader { // 从 SD 卡读取心电图文件

public final static int numChannels = 12;   // the data is stored in 12 channels, one for each lead
public final static int numSamples = 6; //500 = fs so *6 for 6 seconds of data
public File file;
private Scanner scanner;
short [] [] ecg = new short [numChannels] [numSamples];

 public ECGFilereader (String fname) throws FileNotFoundException 
 {
    File file = new File(Environment.getExternalStorageDirectory() +"/1009856.txt");        //accesses the ecg file from the SD card

    scanner = new Scanner(file);

    scanner.useDelimiter(",");  
}
public boolean ReadFile(Waveform[] waves) // sorts data into and array of an array (12 channels each containing 5000 samples)
{
    for (int m=0; m<numSamples && scanner.hasNextInt(); m++)        //
    {
        scanner.nextInt();

        for (int chan = 0; chan<numChannels && scanner.hasNextInt(); chan++)    //&& scanner.hasNextInt()
        {
            ecg [chan] [m] = (short) scanner.nextInt();     

            if (!scanner.hasNextInt())
            {
                if (scanner.hasNextLine())
                {
                    scanner.nextLine();
                    //scanner.nextInt();
                }
            }
        }
        if (!scanner.hasNextInt())
        {
            if (scanner.hasNextLine())
            {
                scanner.nextLine();
                //scanner.nextInt();
            }
        }
    }
4

3 回答 3

1

当设置为时,分隔符仍然没有拾取行尾scanner.useDelimiter(",|\\n");

我无法解释确切原因,但事实证明我也需要在其中添加 \r ,例如:

scanner.useDelimiter(",|\\r\\n");
于 2011-08-23T10:13:18.397 回答
1

应该是scanner.useDelimiter(",|\\n"); 因为您希望编译器将“\n”而不是“\n”放在字符串中,编译器会将\视为转义字符。

于 2011-08-19T15:18:14.223 回答
0

试试这样:

public boolean ReadFile(Waveform[] waves) {
    while(scanner.hasNextInt()){
        if(scanner.hasNextInt()){
            ecg [chan] [m] = (short) scanner.nextInt();
        }
        if(scanner.hasNextLine()){
            scanner.nextLine(); 
        }       
    }
}
于 2011-08-19T10:36:29.743 回答