import java io FileNotFoundException
import java io IOException
import java io RandomAccessFile
public class FromEndRF {
public static void read(String filename) {
read(filename GBK )
}
public static void read(String filename String charset) {
RandomAccessFile rf = null
try {
rf = new RandomAccessFile(filename r )
long len = rf length()
long start = rf getFilePointer()
long nextend = start + len
String line
rf seek(nextend)
int c =
while (nextend >start) {
c = rf read()
if (c == \n || c == \r ) {
line = rf readLine()
if (line != null) {
System out println(new String(line getBytes( ISO ) charset))
}else {
System out println(line) // 输出为null 可以注释掉
}
nextend
}
nextend
rf seek(nextend)
if (nextend == ) {// 当文件指针退至文件开始处 输出第一行
System out println(new String(rf readLine() getBytes( ISO ) charset))
}
}
} catch (FileNotFoundException e) {
e printStackTrace()
} catch (IOException e) {
e printStackTrace()
} finally {
try {
if (rf != null)
rf close()
} catch (IOException e) {
e printStackTrace()
}
}
}
public static void main(String args[]) {
read( d:\\ txt gbk )
}
lishixinzhi/Article/program/Java/hx/201311/26379public static String readLastLine(File file) throws IOException {
if (!file.exists() || file.isDirectory() || !file.canRead()) {
return null
}
RandomAccessFile raf = null
try {
raf = new RandomAccessFile(file, "r")
long len = raf.length()
if (len == 0L) {
return ""
} else {
long pos = len - 1
while (pos > 0) {
pos--
raf.seek(pos)
if (raf.readByte() == '\n') {
break
}
}
if (pos == 0) {
raf.seek(0)
}
byte[] bytes = new byte[(int) (len - pos)]
raf.read(bytes)
return new String(bytes)
}
} catch (FileNotFoundException e) {
e.printStackTrace()
} finally {
if (raf != null) {
try {
raf.close()
} catch (Exception ea) {
ea.printStackTrace()
}
}
}
return null
你可以先定义一个inputstreamreader读取文本文件内容,然后再用一个linenumberreader获取刚才inputstreamreader的对象,linenumberreader里有个方法readline()是用来一行一行的顺序读取字符,然后用一个判断语句来判断你想修改的行,最后删除或修改就可以了欢迎分享,转载请注明来源:内存溢出
评论列表(0条)