当前位置:首页 » 编程语言 » java文本读取

java文本读取

发布时间: 2022-05-06 20:50:50

‘壹’ java如何读取一个txt文件的所有内容

importjava.io.BufferedInputStream;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.InputStreamReader;
importjava.io.Reader;


publicclassH{
/**
*功能:Java读取txt文件的内容
*步骤:1:先获得文件句柄
*2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
*3:读取到输入流后,需要读取生成字节流
*4:一行一行的输出。readline()。
*备注:需要考虑的是异常情况
*@paramfilePath
*/
publicstaticvoidreadTxtFile(StringfilePath){
try{
Stringencoding="GBK";
Filefile=newFile(filePath);
if(file.isFile()&&file.exists()){//判断文件是否存在
InputStreamReaderread=newInputStreamReader(
newFileInputStream(file),encoding);//考虑到编码格式
BufferedReaderbufferedReader=newBufferedReader(read);
StringlineTxt=null;
while((lineTxt=bufferedReader.readLine())!=null){
System.out.println(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
}catch(Exceptione){
System.out.println("读取文件内容出错");
e.printStackTrace();
}

}

publicstaticvoidmain(Stringargv[]){
StringfilePath="L:\20121012.txt";
//"res/";
readTxtFile(filePath);
}}

‘贰’ JAVA中读取文件(二进制,字符)内容的几种方

JAVA中读取文件内容的方法有很多,比如按字节读取文件内容,按字符读取文件内容,按行读取文件内容,随机读取文件内容等方法,本文就以上方法的具体实现给出代码,需要的可以直接复制使用

public class ReadFromFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
// 一次读多个字节
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}

/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 对于windows下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}

} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}

/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}

/**
* 随机读取文件内容
*/
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("随机读取一段文件内容:");
// 打开一个随机访问文件流,按只读方式
randomFile = new RandomAccessFile(fileName, "r");
// 文件长度,字节数
long fileLength = randomFile.length();
// 读文件的起始位置
int beginIndex = (fileLength > 4) ? 4 : 0;
// 将读文件的开始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
// 将一次读取的字节数赋给byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}

/**
* 显示输入流中还剩的字节数
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
ReadFromFile.readFileByBytes(fileName);
ReadFromFile.readFileByChars(fileName);
ReadFromFile.readFileByLines(fileName);
ReadFromFile.readFileByRandomAccess(fileName);
}
}

‘叁’ 如何用java读取txt文件的内容

import java.io.*; public class Read{ public static void main(String [] args) { try{

FileReader f = new FileReader("D:\\1.txt"); // 注意路径这里可以有两种表示方法一个种\\一种/就可以了 BufferedReader buf = new BufferedReader(f);

String s; while((s = buf.readLine() ) != null){ System.out.println(s); } f.close(); buf.close();

}catch(IOException e){} }}

‘肆’ java文件如何读取

有几种方法读取吧
File
file
=
new
File("d:\\a.txt");//把D盘目录下的a.txt读取出来,
InputStream
is
=
new
FileInputStream(file);//把文件以字节流读到内存中
第二种是类加载
Demo1.class.getClassLoader().getResourceAsStream("a.txt");//Demo1为当前类名,a.txt在与Demo1.class在同一目录下。
还有其它的就不说了

‘伍’ java读取txt的数据并处理

直接给你一段实际可以用的代码吧

/**
*读取一行一行的文件
*
*@paramfilename
*@return
*@throwsIOException
*/
publicstaticList<String>readLinedFile(Stringfilename){
List<String>filecon=newArrayList<String>();
Stringm="";
BufferedReaderfile=null;
try{
file=newBufferedReader(newFileReader(filename));
while((m=file.readLine())!=null){
if(!m.equals(""))//不需要读取空行
{
filecon.add(m);
}
}
file.close();
}catch(IOExceptione){
e.printStackTrace();
}

returnfilecon;
}

这段代码实现了,你传入文件的路径,给你读出一个String的List,一个String就是文件的一行,拿到这个List,你爱怎么处理就怎么处理,就比如你现在这个需求吧,就把这个List拿来遍历

//这个是去除不含genotype字符串后的数组
List<String>resultList=newArrayList<String>();
for(Stringline:filecon){
if(line.indexOf("genotype")!=-1){
resultList.add(line);
}
}

这样处理完后就拿到了一个只有含有 genotype的数组,然后剩下的就是把这个数组写到一个文件里面,我给你看一个把字符串数组写到文件的方法,你可以拿去直接用

/**
*写入一行一行的文件
*@paramlst要写入的字符串数组
*@paramfilename要写入的文件路径
*@return
*@throwsIOException
*/
(Listlst,StringfilePath)throwsIOException{
Filefile=newFile(filePath);
BufferedWriterout=newBufferedWriter(newFileWriter(file,false));
for(inti=0;i<lst.size();i++){
Stringtemp=(String)lst.get(i);
if(!StringUtils.isBlank(temp)){
out.write(temp);
out.newLine();
}
}
out.close();
out=null;
file=null;
}

这样懂了吧?

‘陆’ Java 如何读取txt文件的内容

java读取txt文件内容。可以作如下理解:

  • 首先获得一个文件句柄。File file = new File(); file即为文件句柄。两人之间连通电话网络了。接下来可以开始打电话了。

  • 通过这条线路读取甲方的信息:new FileInputStream(file) 目前这个信息已经读进来内存当中了。接下来需要解读成乙方可以理解的东西

  • 既然你使用了FileInputStream()。那么对应的需要使用InputStreamReader()这个方法进行解读刚才装进来内存当中的数据

  • 解读完成后要输出呀。那当然要转换成IO可以识别的数据呀。那就需要调用字节码读取的方法BufferedReader()。同时使用bufferedReader()的readline()方法读取txt文件中的每一行数据哈。

packagecom.campu;

importjava.io.BufferedInputStream;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.InputStreamReader;
importjava.io.Reader;

/**
*@authorJava团长
*H20121012.java
*2017-10-29上午11:22:21
*/
publicclassH20121012{
/**
*功能:Java读取txt文件的内容
*步骤:1:先获得文件句柄
*2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
*3:读取到输入流后,需要读取生成字节流
*4:一行一行的输出。readline()。
*备注:需要考虑的是异常情况
*@paramfilePath
*/
publicstaticvoidreadTxtFile(StringfilePath){
try{
Stringencoding="GBK";
Filefile=newFile(filePath);
if(file.isFile()&&file.exists()){//判断文件是否存在
InputStreamReaderread=newInputStreamReader(
newFileInputStream(file),encoding);//考虑到编码格式
BufferedReaderbufferedReader=newBufferedReader(read);
StringlineTxt=null;
while((lineTxt=bufferedReader.readLine())!=null){
System.out.println(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
}catch(Exceptione){
System.out.println("读取文件内容出错");
e.printStackTrace();
}

}

publicstaticvoidmain(Stringargv[]){
StringfilePath="L:\Apache\htdocs\res\20121012.txt";
//"res/";
readTxtFile(filePath);
}}
我有一个微信公众号,经常会分享一些Java技术相关的干货文章,还有一些学习资源。
如果你需要的话,可以用微信搜索“Java团长”或者“javatuanzhang”关注。

‘柒’ java怎么读取文本文件中的所有字符

可以用文件流FileInputStream的方式读取,如果文本文件太大了,不建议一次性往内存中读,那往往会使之溢出。也可以一行行的读取,用BufferReader读,具体的实例都可以网络得到的。

‘捌’ java读取文本文档

//仅提供一些关键语句,不可直接运行,具体自己去实现
//自己多查查Java API
import java.io.*;//导入操作要用到的类
File file=new File("c:/test.txt");//源文件位置
FileReader fr=new FileReader(file);//创建文件输入流
BufferedReader in=new BufferedReader(fr);//包装文件输入流,可整行读取
String line;
while((line=in.readLine()) != null) {
//循环里逐行读取到字符串line
String[] str=line.split(" ")//以空格为间隔将这一行拆分成一组小字符串
int []num=new int[100];
num[i]=Integer.parseInt(str[i]);//将拆分的字符串解析为整数
int sum=num[0]+num[1]
//进行运算操作
}

‘玖’ java如何读取txt文件内容

给你两个方法,你可以看看;
//获取值返回String文本
publicStringtxt2String(StringfilePath){
Filefile=newFile(filePath);
StringBuilderresult=newStringBuilder();
try{
BufferedReaderbr=newBufferedReader(newFileReader(file));//构造一个BufferedReader类来读取文件
Strings=null;
while((s=br.readLine())!=null){//使用readLine方法,一次读一行
result.append(s+System.lineSeparator());
}
br.close();
}catch(Exceptione){
e.printStackTrace();
}
returnresult.toString();
}

//获取值不返回String文本
publicvoidreadTxtFile(StringfilePath){
try{
Stringencoding="GBK";
Filefile=newFile(filePath);
if(file.isFile()&&file.exists()){//判断文件是否存在
InputStreamReaderread=newInputStreamReader(
newFileInputStream(file),encoding);//考虑到编码格式
BufferedReaderbufferedReader=newBufferedReader(read);
StringlineTxt=null;
while((lineTxt=bufferedReader.readLine())!=null){
System.out.println(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
}catch(Exceptione){
System.out.println("读取文件内容出错");
e.printStackTrace();
}
}

热点内容
kindeditor上传图片绝对路径 发布:2025-05-14 01:06:27 浏览:276
广数g96编程实例 发布:2025-05-14 01:01:56 浏览:912
安卓手机如何做一个小程序 发布:2025-05-14 01:01:51 浏览:969
linux怎么访问外网 发布:2025-05-14 01:00:24 浏览:953
玩dnf什么配置不卡卡 发布:2025-05-14 00:57:02 浏览:807
android优秀项目源码 发布:2025-05-14 00:54:58 浏览:206
dell服务器怎么装系统 发布:2025-05-14 00:50:52 浏览:594
csgo怎么进日本服务器 发布:2025-05-14 00:39:18 浏览:749
ip查服务器商家 发布:2025-05-14 00:33:37 浏览:213
云服务器布 发布:2025-05-14 00:27:55 浏览:79