从文本文件获取int并将其设置为变量 [英] Get int from text file and set it to variable
问题描述
我正在尝试获取文本文件的int值,该文本的内容如下:
I'm trying to get the int value of a text file that have text like:
123456789 12345678 1234567 123456 12345 1234 123 12 1
如您所见,每个数字都是不同的,它们在同一行中,并用空格"分隔.我需要将值分开.得到这样的东西:
as you can see every number is different and they are in a same line separated by a "space". I need to get the values separated. to get something like this:
INT1 = 123456789,INT2 = 12345678,INT3 = 1234567;
,依此类推.我没有创建文本,所以我不知道它们是多少个数字和组,但是它们始终由空格"分隔.我知道该怎么读.这就是我的阅读方式:
and so on. I don't create the text so I don't know how much numbers and groups they are, but they are always separated by a "space". I know how to read it. This is how I'm reading it:
try {
TEST1 = new BufferedReader(new FileReader("/sdcard/test.txt")).readLine();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TEST.setText(""+scaling_available_frequencies);
我得到了这个输出
194208 776175 958253 767883 700246 243663 966618 345199 945363 459833
注意:这只是我创建的test.txt,以查看其是否有效.当前代码将要求用户输入路径和文件名.
NOTE: This is just a test.txt that I created to see if it works. The current code will ask the user for entering path and file name.
现在如何将它们设置为每个组的变量?
Now how can I set them to a variable per group?
谢谢
推荐答案
这是将String解析为整数数组的一种方法:
This is one way to parse the String to an integer array:
public int[] toIntArray( String stringFromFile ){
String[] allStrings = stringFromFile.split( "\\s" );
int[] intArray = new int[allStrings.length];
for( int i = 0; i < allStrings.length; ++i ){
try{
intArray[i] = Integer.parseInt( allStrings[i] );
}catch( NumberFormatException e ){
// Do whatever you think is appropriated
intArray[i] = -1;
}
}
return intArray;
}
希望这会有所帮助.
这篇关于从文本文件获取int并将其设置为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!