一、如果用最笨的方法的是逐行读文件的每一行,然后给数组赋值,但是事先不知道应该new个多少个比较合适。这个时候就得用到ArrayList, ArrayList是可调整大小的数组,等效于C ++ Vector。
二、看下面小例子
1、java code
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> res = new ArrayList<>();
res.add("English");
res.add("Japan");
res.add("USA");
// 要定义数组的长度
String str[] = res.toArray(new String[res.size()]);
for (String s : str) {
System.out.println(s);
}
}
}
2、run output
English
Japan
USA
三、实际工作中运用,读取文本文件的每一行并将每一行设置为数组元素。
public static String[] ReadCFGFile(String strFilePath)
{
String path = strFilePath;
String content = ""; //文件内容字符串
//打开文件
File file = new File(path);
List<String> str= new ArrayList<>();
//如果path是传递过来的参数,可以做一个非目录的判断
if (file.isDirectory()) {
Log.d(TAG, "The File doesn't not exist.");
}
else
{
try {
InputStream instream = new FileInputStream(file);
if (instream != null)
{
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
//分行读取
while (( line = buffreader.readLine()) != null) {
content += line + "\n";
str.add(line);
}
instream.close();
}
}
catch (java.io.FileNotFoundException e)
{
Log.d(TAG, "The File doesn't not exist.");
}
catch (IOException e)
{
Log.d(TAG, e.getMessage());
}
}
String data[] = str.toArray(new String[str.size()]);
for (String s : str) {
Log.d(TAG, s);
}
return data;
}
int n=0;
String[] cfg_data;
cfg_data = ReadCFGFile("/sdcard/continuous.cfg");
n = cfg_data.length;
for(int i=0;i<n;i++){
Log.d(TAG, "cfg_data:" + cfg_data[i]);
}
02-24 13:27:42.695 19665 19665 D NETCAP-MAINACTIVITY: 0.12 100 20
02-24 13:27:42.695 19665 19665 D NETCAP-MAINACTIVITY: 2.120 100 20
02-24 13:27:42.695 19665 19665 D NETCAP-MAINACTIVITY: 5.0 100 20
02-24 13:27:42.695 19665 19665 D NETCAP-MAINACTIVITY: cfg_data:0.12 100 20
02-24 13:27:42.695 19665 19665 D NETCAP-MAINACTIVITY: cfg_data:2.120 100 20
02-24 13:27:42.695 19665 19665 D NETCAP-MAINACTIVITY: cfg_data:5.0 100 20
四、参考文章