例如
读取文件a.txt,要求将a.txt中从<table>到</table>中的内容读到字符串里,如何实现??

解决方案 »

  1.   

    可以使用RandomAccessFile,但是要定位到<table>的位置其实还是要从之前开始读
      

  2.   

    看你的实际文件情况和需求情况了,看你文件中是不是就这么一个<table>****</table>标签,如果是就很容易,如果还有其他的而你只想改其中一个就有难度。
      

  3.   

    ? 文件格式是 xml 的么?如果是那直接用xml解析器好了
      

  4.   

    被人说的文件格式是txt:
    /**
     * 读取文件的指定部分
     * */
    import java.io.File;
    import java.io.FileInputStream;
    public class Test7 {
    public static void main(String[] src) throws Exception{
    /*读取文件*/
    FileInputStream myfile = new FileInputStream(
    new File("a.txt"));

    byte[] filebyte = new byte[(int)new File("a.txt").length()];
    myfile.read(filebyte);
    String filecontent = new String(filebyte);

    /*以下开始寻找需要的内容*/
    int beginindex = filecontent.indexOf("<table>") + 7;
    int endindex = filecontent.indexOf("</table>");
    System.out.println(filecontent.substring(beginindex,endindex));
    }
    }
    测试有效
      

  5.   

    RandomAccessFile一般是用来操作二进制文件的,对于文本文件,一般的做法是用类
    似BufferedReader类从头读取
      

  6.   

    RandomAccessFile类
    seek(long pos)方法为指向指定位置read(byte b[], int off, int len):
    read(mybyte,0,1024);意思是在文件的pos位置处(注意这里的0不是指从文件开头,而是指从指定位置开始),读入长度为1024的mybyte数组的数据。当然使用BufferedReader也是可以的,Java里面的Reader,writer都是对于处理字符char而言的,而stream,file是对于byte而言的。
      

  7.   

    我目前就采用 yinwenjie(java入门中)的方法,可是用RandomAccessFile怎么处理呢?
      

  8.   

    RandomAccessFile recFile = new RandomAccessFile("c:/aaa.sql", "r");
    while (true) {
        String line1 = recFile.readLine();
        //一行一行读,比较安全
    String line = "";
    if (line1 == null)
    break;
    while (line1 != null) {
    line = line + line1;
    if (line.indexOf(";") >= 0) {
    //遇到分号,执行sql,<table>你自己改改
    line = line.substring(0, line.length() - 1);
    stmt.executeUpdate(line);
    line="";
    }
    line1 = recFile.readLine();
    }

    }
      

  9.   

    用RandomAccessFile也可以,一样有一个定位的过程,而且显得有些多此一举
    class test{
    public static void main(String[] src) throws Exception{
    RandomAccessFile myfile = new RandomAccessFile(new File("a.txt"),"rw");
    byte[] filebyte = new byte[(int)myfile.length()];
    myfile.read(filebyte);

    String filecontent = new String(filebyte);
    /*开始定位*/
    int beginindex = filecontent.indexOf("<table>") + 7;
    int endindex = filecontent.indexOf("</table>");
    myfile.seek(beginindex);

    /*从RandomAccessFile中读数据*/
    filebyte = new byte[endindex - beginindex];
    myfile.read(filebyte);

    }
    }