从JAVA中如何读取记事本的数据,我只能读取一列多行的,对于多行多列的不知该如何处理
以下是我读取一列多行的程序,大家帮忙改一下吧,改成能够实现读取多行多列。
// 2. 首先从文本文件中读取串号信息,保存到动态数组中
ArrayList SnList = new ArrayList(); FileReader freader = null;
try
{
freader=new FileReader(file);
}
catch(FileNotFoundException fe)
{
throw new Exception("文件 "+file+" 不存在");
}
BufferedReader bread = new BufferedReader(freader); // 建立BufferedReader对象
String Line = bread.readLine(); // 从文件读取一行字符串 while(Line!=null) // 判断读取到的字符串是否不为空
{
SnList.add(Line.trim()); // 输出从文件中读取的数据
Line=bread.readLine(); // 从文件中继续读取一行数据
}
bread.close(); // 关闭BufferedReader对象
freader.close(); // 关闭文件

解决方案 »

  1.   

    import java.util.StringTokenizer;
    import java.util.Enumeration;/*
     * A Powerful Tokenizer
     * Author Bhabani Padhi
     */
    public class PowerfulTokenizer implements Enumeration
    {
    private String sInput;
    private String sDelim;
    private boolean bIncludeDelim = false;
    private StringTokenizer oTokenizer;
    private int iEndQuote = 0;
    private String sPrevToken = "";
    private int iTokenNo = 0;
    private int iTotalTokens = 0;
    private int iTokens = 0;
    private int iLen = 0; /**
     * Constructor
     *
     * @param str the input string
     * @param sep the delimiter string
     */
    public PowerfulTokenizer(String str, String sep)
    {
    sInput = str;
    sDelim = sep;
    iLen = sDelim.length();
    oTokenizer = new StringTokenizer(str, sep, true);
    } /**
     * Constructor
     *
     * @param str the input string
     * @param sep the delimiter string
     * @param bIncludeDelim if true, include delimiters as tokens
     */
    public PowerfulTokenizer(String str, String sep, boolean bIncludeDelim)
    {
    sInput = str;
    sDelim = sep;
    this.bIncludeDelim = bIncludeDelim;
    iLen = sDelim.length();
    oTokenizer = new StringTokenizer(str, sep, true);
    } /**
     * Returns the next token from the input string.
     *
     * @return String the current token from the input string.
     */
    public String nextToken()
    {
    String sToken = oTokenizer.nextToken();

    // return "" as token if consecutive delimiters are found.
    if ( (sPrevToken.equals(sDelim)) && (sToken.equals(sDelim)) )
    {
    sPrevToken = sToken;
    iTokenNo++;
    return "";
    } // check whether the token itself is equal to the delimiter and
    // present in a substring
    if ( (sToken.trim().startsWith("\"")) && (sToken.length() == 1) )
    {
    // this is a special case when token itself is equal to delimeter
    String sNextToken = oTokenizer.nextToken();
    while (!sNextToken.trim().endsWith("\""))
    {
    sToken += sNextToken;
    sNextToken = oTokenizer.nextToken();
    }
    sToken += sNextToken;
    sPrevToken = sToken;
    iTokenNo++;
    return sToken.substring(1, sToken.length()-1);
    }
    // check whether there is a substring inside the string
    else if ( (sToken.trim().startsWith("\"")) 
    && (!((sToken.trim().endsWith("\"")) 
    && (!sToken.trim().endsWith("\"\"")))) )
    {
    if (oTokenizer.hasMoreTokens())
    {
    String sNextToken = oTokenizer.nextToken();
    //System.out.println("next token = " + sNextToken 
    // + ", token = " + sToken);
    // the reason it checks for presence of "\"\"" is 
    // you get this while converting a excel file to csv file
    // if the excel file contains a "\""
    while (!((sNextToken.trim().endsWith("\"")) 
    && (!sNextToken.trim().endsWith("\"\""))) )
    {
    sToken += sNextToken;
    if (!oTokenizer.hasMoreTokens())
    {
    sNextToken = "";
    break;
    }
    sNextToken = oTokenizer.nextToken();
    }
    sToken += sNextToken;
    }
    }

    sPrevToken = sToken;
    // remove any unnecessary double quote still present.
    if (sToken.length() > 0)
    {
    sToken = sToken.trim();
    // remove double quote s from beginning and end of the string
    if (sToken.charAt(0) == '"' 
    && sToken.charAt(sToken.length()-1) == '"')
    sToken = sToken.substring(1, sToken.length()-1);

    String sTemp = "";
    int iPrevDblQuote = 0;
    int iDblQuote = sToken.indexOf("\"\"");
    // change "\"\""'s to "\"" if any of them are present
    if (iDblQuote != -1)
    {
    String sDummy = sToken;
    while (iDblQuote != -1)
    {
    sTemp = sDummy.substring(0, iDblQuote+1);
    sTemp += sDummy.substring(iDblQuote+2);
    iPrevDblQuote = iDblQuote;
    sDummy = sTemp;
    iDblQuote = sDummy.indexOf("\"\"", iPrevDblQuote+1);
    }
    sToken = sTemp;
    }
    }

    // call next token again, if delimeters are not to be included
    // as tokens.
    if ( (!bIncludeDelim) && (sToken.equals(sDelim)) )
    {
    sToken = nextToken();
    }
    else
    iTokenNo++; //System.out.println("idx = " + iTokenNo + ", token = " + sToken);
    return sToken;
    } /**
     * Checks whether any token is left in the input string
     *
     * @return boolean true, if any token is left
     */
    public boolean hasMoreTokens()
    {
    if (iTotalTokens == 0)
    iTotalTokens = countTokens(); return (iTokenNo < iTotalTokens);
    } /**
     * Checks whether any token is left in the input string
     *
     * @return boolean true, if any token is left
     */
    public boolean hasMoreElements()
    {
    return hasMoreTokens();
    } /**
     * Returns the next token from the input string.
     *
     * @return Object the current token from the input string.
     */
    public Object nextElement()
    {
    return nextToken();
    } /**
     * Total number of tokens present in the input string
     *
     * @return int total number of tokens
     */
    public int countTokens()
    {
    //int iTokens = super.countTokens();
    iTokens = oTokenizer.countTokens();
    int iActualTokens = iTokens;
    System.out.println("original tokens = " + iTokens);
    int[] aiIndex = new int[iTokens];
    aiIndex[0] = 0;
    int iIndex = 0;
    int iNextIndex = 0;
    // check whether the delimiter is within a substring
    for (int i=1; i<aiIndex.length; i++)
    {
    iIndex = sInput.indexOf(sDelim, iIndex+1);
    if (iIndex == -1)
    break;
    // if the delimiter is within a substring, then parse upto the
    // end of the substring.
    while (sInput.substring(iIndex-iLen, iIndex).equals(sDelim))
    {
    iNextIndex = sInput.indexOf(sDelim, iIndex+1);
    if (iNextIndex == -1)
    break;
    iIndex = iNextIndex;
    }
    aiIndex[i] = iIndex;
    //System.out.println("aiIndex[" + i + "] = " + iIndex);
    if (isWithinQuotes(iIndex))
    {
    if (bIncludeDelim)
    iTokens -= 2;
    else
    iTokens -= 1;
    }
    } if (bIncludeDelim)
    {
    return iTokens;
    }
    else if ( (!bIncludeDelim) || (iTokens == iActualTokens) )
    {
    // remove the number of actual delimeters from 
    // the string as this a case with bIncludeDelim=false
    int iIdx = 0;
    iIdx = sInput.indexOf(sDelim, iIdx+1);
    while (iIdx != -1)
    {
    if ( !((sInput.charAt(iIdx-1) == '"') 
    && (sInput.charAt(iIdx+1) == '"') 
    && ( (iIdx+1+iLen <= sInput.length()) 
    && (sInput.substring(iIdx+1, iIdx+1+iLen).equals(sDelim)))) )
    {
    iTokens--;
    } // don't decrement the token count if consecutive tokens 
    // are found.
    while ( (iIdx+1 < sInput.length()) && 
    (sInput.substring(iIdx+1, iIdx+1+iLen).equals(sDelim)) )
    {
    iIdx += iLen;
    }
    iIdx = sInput.indexOf(sDelim, iIdx+1);
    }
    } return iTokens;
    }

    /**
     * Checks whether the particular index (at which the delimiter is found
     * is within double quotes (i.e. in a substring). This also checks 
     * whether the token is equal to the delimeter.
     *
     * @return boolean true, if the index is within a substring
     */
    private boolean isWithinQuotes(int k)
    {
    int iStartQuote = sInput.indexOf("\"", 0);
    //System.out.println("quote = " + iStartQuote); if (k < iStartQuote)
    return false; if (!bIncludeDelim)
    {
    // check whether token is equal to delimiter
    if ( (sInput.charAt(k-1) == '"') && (sInput.charAt(k+1) == '"') 
    && ((k+1+iLen <= sInput.length()) 
    && (sInput.substring(k+1, k+1+iLen).equals(sDelim))) )
    {
    iTokens -= 2;
    return false;
    }
    } while (iStartQuote != -1)
    {
    iEndQuote = sInput.indexOf("\"", iStartQuote+1);

    if ( k > iStartQuote && k < iEndQuote )
    {
    // delimiter is within a substring
    return true;
    } iStartQuote = sInput.indexOf("\"", iEndQuote+1);
    }

    return false;
    }
    }
      

  2.   

    我这个简单一些
    //TextFileReader.java
    package textfileaccess;
    import java.io.*;
    import java.awt.event.*;
    import java.util.*;
    /**
    * TextFileReader是一个提供基本的读取文本文件功能 
    * 的Bean类.
    */
    public class TextFileReader {
    private String fileName, errorMessage;
    private int columns, rowCount; 
    /**
    * TextFileReader的结构函数.
    */
    public TextFileReader() {
    reset(); 
    }
    /**
    * 重置该Bean中的所有变量.
    */
    public void reset() {
    fileName = "";
    errorMessage = "";
    columns = 0;
    rowCount = 0;
    }
    /**
    * 当错误产生时,设置错误信息.
    */
    public void setErrorMessage(String errorMessage) {
    this.errorMessage = errorMessage;
    }
    /**
    * 返回错误信息.
    */
    public String getErrorMessage() {
    return errorMessage;
    }
    /**
    * 返回文件名.
    */
    public String getFileName() {
    return fileName;
    }
    /**
    * 设置文件名.
    */
    public void setFileName(String fileName) {
    this.fileName = fileName;
    }
    /**
    * 返回文件的行数.
    */
    public int getRows() {
    return rowCount;
    }
    /**
    * 返回文件中最大一行的列数.
    */
    public int getColumns() {
    return columns;
    }
    /**
    * 将文件内容返回到一个字符串中.
    * 如果有错误产生, 例如文件不存在, 将返回null.
    */
    public String getContent() {
    String content = "";
    File file = new File(fileName);
    if (!file.exists()) {
    setErrorMessage("Error: The file '" + fileName + "' does not exists.");
    return null;

    else if (file != null) {
    try {
    // 创建一个BufferedReader对象,这样每次可以读取一行.
    BufferedReader reader = new BufferedReader(
    new FileReader(file));
    String inLine = reader.readLine();
    while (inLine != null) {
    if (inLine.length() + 1 > columns)
    columns = inLine.length() + 1;
    content += (inLine +
    System.getProperty("line.separator"));
    inLine = reader.readLine();
    rowCount++;
    }
    return content;
    }
    catch (IOException e) {
    setErrorMessage("Error reading the file: " + e.getMessage());
    return null;
    }
    }
    else {
    setErrorMessage("Unknown error!");  return null;
    }
      }
    }<!--
    TextFileReader.jsp
    -->
    <%@ page import = "textfileaccess.TextFileReader" %>
    <jsp:useBean id="file_reader" class="textfileaccess.TextFileReader" scope="session"/>
    <jsp:setProperty name="file_reader" property="fileName"/>
    <html>
    <head><title>Read a text file</title></head>
    <body bgcolor="white">
    <font size=4>
    <%
    if (file_reader.getFileName() != "")

    %>
    The content of the file '
    <% out.println(file_reader.getFileName()); %>' : <br><br>
    <%
    if (file_reader.getContent() != null)

    %>
    <Form>
    <TEXTAREA rows=<%= file_reader.getRows() %> cols=<%= file_reader.getColumns() %> id=textarea1 name=textarea1>
    <% out.println(file_reader.getContent()); %>
    </TEXTAREA>
    </Form>
    <%
    }
    else

     out.println(file_reader.getErrorMessage()); 
    }
    %>
    <br><br>
    <% file_reader.reset(); %>
    Do you want to <a href="TextFileReader.jsp">look at another file</a>?
    <%
    }
    else 

    %>
    Welcome to the 'Read a file in JSP' example.<br>
    The example simply shows the file in a textarea.<p>
    Please fill out what file you want to look at. Be sure to type the complete path.<p>
    <form method=get action="TextFileReader.jsp">
    FileName? <input type=text name=fileName>
    <input type=submit value="Show it!">
    </form>
    <%
    }
    %>
    </font>
    </body>
    </html>
      

  3.   

    jspfans(JSP小学生):columns = inLine.length() + 1;这句话什么意思啊?
      

  4.   

    jragon(杰根) columns = inLine.length() + 1;
    列数等于当前行的长度+1啊,这样才能构造出文件中最大一行的列数啊。不对的话请高手指正。是不是有更高效的方法呢??