private void writeFile()
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(Server.MapPath("mytest.txt")))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
this.TextBox1.Text += "\r\n" + line;
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
//----------------------------------------------------------------------------------------
if (!File.Exists(Server.MapPath(FILE_NAME)))
{
Response.Write("<script language='javascript'> alert('MyFile.txt does not exist.');</script>");
return;
}
using (StreamReader sr = File.OpenText(Server.MapPath(FILE_NAME)))
{
String input;
while ((input = sr.ReadLine()) != null)
{
Console.WriteLine(input);
}
Console.WriteLine("The end of the stream has been reached.");
}
//-----------------------------------------------------
info.txt内容
HOUSING_1_Y,8,0c50ea59-60f8-11e0-ab60-001aa02db7e0,1
HOUSING_1_Y,0c50ea59-60f8-11e0-ab60-001aa02db7e0,2
HOUSING_1_Y,0c50ea59-60f8-11e0-ab60-001aa02db7e0,3
HOUSING_1_Y,0c50ea59-60f8-11e0-ab60-001aa02db7e0,4
HOUSING_1_Y,0c50ea59-60f8-11e0-ab60-001aa02db7e0,5
HOUSING_1_Y,0c50ea59-60f8-11e0-ab60-001aa02db7e0,6
HOUSING_1_Y,0c50ea59-60f8-11e0-ab60-001aa02db7e0,7
public static void main(String[] args) {
{
String fileName = "c:\\temp\\info.txt";// 要读取的txt文件
String sId;
List<String[]> list = getFileContent(fileName);// 将所有读到的文件放到数组里面
String[] ary = list.get(0);// 获取数组的第1行HOUSING_1_Y,8,0c50ea59-60f8-11e0-ab60-001aa02db7e0,1
for (String str : ary) {
System.out.println(str);输出数组的第1行HOUSING_1_Y,8,0c50ea59-60f8-11e0-ab60-001aa02db7e0,1
System.out.println(str.split(","));
/*输出的值如下:HOUSING_1_Y 8 0c50ea59-60f8-11e0-ab60-001aa02db7e0 1*/
ary=str.split(",");
sId=ary[1];//输出数组的第1行第二列8;
System.out.println(ary[1]);//输出数组的第1行第二列8;
}
//request.setAttribute("id",listForm.s);
return null;
}
private static List<String[]> getFileContent(String fileName)
throws FileNotFoundException, IOException {
File file = new File(fileName);
BufferedReader bf = new BufferedReader(new FileReader(file));
String content = "";
List<String[]> contentList = new ArrayList<String[]>();
while (content != null) {
content = bf.readLine();
System.out.println(content);
if (content == null) {
break;
}
if (!content.trim().equals("")) {
contentList.add(content.trim().split("\\s+"));
}
}
bf.close();
return contentList;
}
}