从一行文件中获取字符串?

时间:2016-04-14 05:21:48

标签: java string file-io java.util.scanner bufferedreader

目前,要从文件中找到我想要的行,我将逐行读取文件,直到我要查找的字符串与当前行匹配。

这似乎是糟糕的编码习惯,因为我的文件是1000多行;有没有办法告诉扫描仪或缓冲读卡器(或其他什么?),从给定行的字符创建一个字符串?

编辑:似乎ajb指出这在物理上是不可能的。

我认为最好的解决方案是将整个文件读入一行String []。

3 个答案:

答案 0 :(得分:0)

是的,您可以设置读取或写入文件的偏移量。 使用RandomAccessFile API也是如此。包括下面的示例代码。

import java.io.*;

public class RandomAccessFileDemo {

   public static void main(String[] args) {
      try {
         // create a new RandomAccessFile with filename test
         RandomAccessFile raf = new RandomAccessFile("F:/test.txt", "r");

         System.out.println("Output without setting offset, i.e. from start of file");
         // print the lines
         String temp="";
         while((temp = raf.readLine()) != null)
            System.out.println(temp);

            System.out.println();
         // set the file pointer at 20 position
         raf.seek(20);
            System.out.println("Output using seek and setting offset to 20");
         // print the line
         while((temp = raf.readLine()) != null)
            System.out.println(temp);

      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

这是我的样本test.txt放在F盘

This is an example
Hello World
Trying RandomAccessFile

这是程序的输出

Output without setting offset, i.e. from start of file
This is an example
Hello World
Trying RandomAccessFile

Output using seek and setting offset to 20
Hello World
Trying RandomAccessFile

答案 1 :(得分:0)

尝试使用mutli-threading概念,因为文件中的行数/行数更多。

private void multiThreadRead(int num){

    for(int i=1; i<= num; i++) { 
        new Thread(readIndivColumn(i),""+i).start(); 
     } 
}

private Runnable readIndivColumn(final int colNum){
    return new Runnable(){
        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {

                long startTime = System.currentTimeMillis();
                System.out.println("From Thread no:"+colNum+" Start time:"+startTime);

                RandomAccessFile raf = new RandomAccessFile("./src/test/test1.csv","r");
                String line = "";
                //System.out.println("From Thread no:"+colNum);

                while((line = raf.readLine()) != null){
                    //System.out.println(line);
                    //System.out.println(StatUtils.getCellValue(line, colNum));
                }


                long elapsedTime = System.currentTimeMillis() - startTime;

                String formattedTime = String.format("%d min, %d sec",  
                        TimeUnit.MILLISECONDS.toMinutes(elapsedTime), 
                        TimeUnit.MILLISECONDS.toSeconds(elapsedTime) -  
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(elapsedTime)) 
                    );

                System.out.println("From Thread no:"+colNum+" Finished Time:"+formattedTime);
            } 
            catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println("From Thread no:"+colNum +"===>"+e.getMessage());

                e.printStackTrace();
            }
        }
    };
}

private void sequentialRead(int num){
    try{
        long startTime = System.currentTimeMillis();
        System.out.println("Start time:"+startTime);

        for(int i =0; i < num; i++){
            RandomAccessFile raf = new RandomAccessFile("./src/test/test1.csv","r");
            String line = "";

            while((line = raf.readLine()) != null){
                //System.out.println(line);
            }               
        }

        long elapsedTime = System.currentTimeMillis() - startTime;

        String formattedTime = String.format("%d min, %d sec",  
                TimeUnit.MILLISECONDS.toMinutes(elapsedTime), 
                TimeUnit.MILLISECONDS.toSeconds(elapsedTime) -  
                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(elapsedTime)) 
            );

        System.out.println("Finished Time:"+formattedTime);
    }
    catch (Exception e) {
        e.printStackTrace();
        // TODO: handle exception
    }

}
    public TesterClass() {

    sequentialRead(1);      
    this.multiThreadRead(1);

}

答案 2 :(得分:0)

Java NIO有很多新方法和简单的方法可以完全按照你想要的方式完成:

public List<String> getLinesInFile(File f){
    return Files.readAllLines(f.toPath());
}

或者您可以将其解析为一个大型字符串并使用contains方法进行搜索:

     /**
     * Uses static methods in the Files class of NIO
     * Reads everything in a file, and puts it in a String
     * @param file the file to read
     * @return a String representing the contents of the file
     * @throws IOException "if an I/O error occurs reading from the stream" (Files.readAllBytes javadoc)
     */
    public String readFileContents(File file) throws IOException {
        String filecontents = "";
        filecontents = new String(Files.readAllBytes(Paths.get(file.toURI())));
        return filecontents;
    }

     /**
     * Checks if a string contains another string, ignoring case
     * @param word the string to look for
     * @param contents the string to look for the other string in
     * @return If it does contain the word, returns true. Otherwise returns false. Ignoring case.
     */
    private boolean containsIgnoreCase(String word, String contents) {
        String w = word.toLowerCase();
        String c = contents.toLowerCase();
        return c.contains(w);
    }