本文主要是介绍java 读取文件 两例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1
采用InputStream is = new FileInputStream(File filePath);等输入流的 形式,读取文件并存放在StringBuffer中。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Read ... {
private static String openFile(String filePath) ...{
File f = new File(filePath);
String ee = new String();
System.out.println("Opening file: " + filePath);
try
...{
InputStream is = new FileInputStream(f);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line; // 用来保存每行读取的内容
line = reader.readLine(); // 读取第一行
while (line != null) ...{ // 如果 line 为空说明读完了
buffer.append(line); // 将读到的内容添加到 buffer 中
buffer.append(" "); // 添加换行符
line = reader.readLine(); // 读取下一行
}
// System.out.print(buffer.toString());
ee = buffer.toString();
}
catch (FileNotFoundException e) ...{
e.printStackTrace();
}
catch (IOException e) ...{
e.printStackTrace();
}
return ee;
}
public static void main(String[] args)...{
System.out.print(Read.openFile("l:/fence.log"));
}
}
2 采用支持对随机存取文件的读取和写入 的类 RandomAccessFile,成功读取文件第一行和最后一行。
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Read2222 ... {
public String rea(String descAddr)...{
String result = new String();
RandomAccessFile rf = null;
StringTokenizer st = new StringTokenizer(descAddr,".");
String fileLuJing = st.nextToken() + ".db";
ArrayList<String> ziFu = new ArrayList<String>();//每一行的字符串为一个元素
try ...{
rf = new RandomAccessFile(fileLuJing, "r");
long len = rf.length();
long start = rf.getFilePointer();
//System.out.println(start);
long nextend = start + len - 1;
String eachLine;//用于向ArrayList添加元素的代表
String lastLine;//最后一行的字符串
String firstLine = rf.readLine();
rf.seek(start);
int c = -1;
while (start<nextend) ...{
c = rf.read();
if (c == ' ' || c == ' ') ...{
eachLine= rf.readLine();
ziFu.add(eachLine);
}
rf.seek(start);
start++;
}
rf.close();
lastLine = ziFu.get(ziFu.size()-1);
/** *//*********转置*****/
// System.out.println("firstLine: "+firstLine);
// System.out.println("lastLine: "+lastLine);
StringTokenizer nameToken = new StringTokenizer(firstLine," ");
StringTokenizer valueToken = new StringTokenizer(lastLine," ");
String temp;
while(nameToken.hasMoreTokens() && valueToken.hasMoreTokens() )
...{
// System.out.println(result);
temp = nameToken.nextToken() + " " + valueToken.nextToken() + " " ;
result+= temp ;
}
/** *//*********转置*****/
}
catch (FileNotFoundException e) ...{
e.printStackTrace();
}
catch (IOException e) ...{
e.printStackTrace();
}
finally ...{
try ...{
if (rf != null)
rf.close();
} catch (IOException e) ...{
e.printStackTrace();
}
}
return result;
}
}
特别注意,rf.seek()定位,这条语句的地方; rf.readLine()读取定位点之后的一行,所以第一行的读取在循环之外。
这篇关于java 读取文件 两例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!