易截截图软件、单文件、免安装、纯绿色、仅160KB

Java按指定行数读取文件

package test
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class ReadSelectedLine{
// 读取文件指定行。
static void readAppointedLineNumber(File sourceFile, int lineNumber)
throws IOException {
FileReader in = new FileReader(sourceFile);
LineNumberReader reader = new LineNumberReader(in);
String s = "";
if (lineNumber <= 0 || lineNumber > getTotalLines(sourceFile)) {
System.out.println("不在文件的行数范围(1至总行数)之内。");
System.exit(0);
}
int lines = 0;
while (s != null) {
lines++;
s = reader.readLine();
if((lines - lineNumber) == 0) {
System.out.println(s);
System.exit(0);
}
}
reader.close();
in.close();
}
// 文件内容的总行数。
static int getTotalLines(File file) throws IOException {
FileReader in = new FileReader(file);
LineNumberReader reader = new LineNumberReader(in);
String s = reader.readLine();
int lines = 0;
while (s != null) {
lines++;
s = reader.readLine();
}
reader.close();
in.close();
return lines;
}

/**
* 读取文件指定行。
*/
public static void main(String[] args) throws IOException {
// 指定读取的行号
int lineNumber = 2;
// 读取文件
File sourceFile = new File("D:/java/test.txt");
// 读取指定的行
readAppointedLineNumber(sourceFile, lineNumber);
// 获取文件的内容的总行数
System.out.println(getTotalLines(sourceFile));
}
}


相关文档:

Java NIO API详解

 
Java NIO API详解
在JDK
1.4以前,Java的IO操作集中在java.io这个包中,是基于流的阻塞(blocking)API。对于大多数应用来说,这样的API使用很方
便,然而,一些对性能要求较高的应用,尤其是服务端应用,往往需要一个更为有效的方式来处理IO。从JDK 1.4起,NIO
API作为一个基于缓冲区,并能提供非阻塞(non-blo ......

java中的基本数据类型长度

        char[] cha = operator.toCharArray();
        char ch = cha[0];
        double sum = 0;
        switch (ch) {
      &nb ......

java 时间格式化

import java.text.SimpleDateFormat;
 Date date=new Date();
  DateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  String time=format.format(date);
java.sql.Time now=new java.sql.Time(System.CurrentTimeMillis());
输出短的系统时间 18:34:44 ......

Java Properties 类读取配置文件信息

在我们平时写程序的时候,有些参数是经常改变的,而这种改变不是我们预知的。比如说我们开发了一个操作数据库的模块,在开发的时候我们连接本地的数据库那么 IP ,数据库名称,表名称,数据库主机等信息是我们本地的,要使得这个操作数据的模块具有通用性,那么以上信息就不能写死在程序里。通常我们的做法是用配置文件来解 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号