我正在尝试使用Scanner类读取下面显示的简单文本文件,并将分隔符设置为scanner.useDelimiter(",");
但是您可以看到每行末尾没有逗号,因此扫描程序不会t读取每行的最后一个数字。有人可以建议如何解决这个问题吗?
提前感谢您的帮助。
文本文件:
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
这里也是我的代码: 公共类ECGFilereader {//从SD卡读取ecg文件
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();
}
}
}
答案 0 :(得分:1)
它应该是scanner.useDelimiter(“,| \\ n”); 因为您希望编译器将“\ n”放在字符串而不是“\ n”中,编译器会将\视为转义字符。
答案 1 :(得分:1)
当设置为scanner.useDelimiter(",|\\n");
我无法解释原因,但事实证明我需要在其中添加\ r \ n:
scanner.useDelimiter(",|\\r\\n");
答案 2 :(得分:0)
试试这样:
public boolean ReadFile(Waveform[] waves) {
while(scanner.hasNextInt()){
if(scanner.hasNextInt()){
ecg [chan] [m] = (short) scanner.nextInt();
}
if(scanner.hasNextLine()){
scanner.nextLine();
}
}
}