javafile读取
‘壹’ java中如何通过file程序去读取查询文件中的文件
File类有两个常用方法可以得到文件路径一个是:getCanonicalPath(),另一个是:getAbsolutePath(),可以通过File类的实例调用这两个方法例如file.getAbsolutePath()其中file是File的实例对象。下面是一个具体例子: public class PathTest{ publ...
‘贰’ java 创建file读取file
/***主要是输入流的使用,最常用的写法*@paramfilePath*@return*/publicstaticStringread(StringfilePath){//读取txt内容为字符串StringBuffertxtContent=newStringBuffer();//每次读取的byte数byte[]b=newbyte[8*1024];InputStreamin=null;try{//文件输入流in=newFileInputStream(filePath);while(in.read(b)!=-1){//字符串拼接txtContent.append(newString(b));}//关闭流in.close();}catch(FileNotFoundExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}finally{if(in!=null){try{in.close();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}}returntxtContent.toString();}
‘叁’ 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 File 读取文件
应该是Scanner类的操作问题,在使用Scanner类读文件的时候,要考虑到换行的功能。
我试了下 用下面的方法是可以读完的。
import java.util.* ;
import java.text.* ;
import java.io.* ;
public class ScannerDemo{
public static void main(String args[]){
File f = new File("D:" + File.separator + "test.txt") ; // 指定操作文件
Scanner scan = null ;
try{
scan = new Scanner(f) ;
}catch(Exception e){}
StringBuffer str = new StringBuffer() ;
while(scan.hasNext()){
str.append(scan.next()).append('\n') ;//取数据
}
System.out.println("文件内容为:" + str) ;
}
};
‘伍’ java中怎样从一个文件中读取文件信息
java读取文件路径、所占空间大小等文件消息,主要是使用FileInputStream类来操作,示例如下:
importjava.io.File;
importjava.io.FileInputStream;
publicclassceshi{
publicstaticvoidmain(String[]args)throwsException{
java.io.FilelocalFile=newFile("D:\1.txt");
FileInputStreamins=newFileInputStream(localFile);
intcountLen=ins.available();
byte[]m_binArray=newbyte[countLen];
ins.read(m_binArray);
ins.close();
System.out.println(localFile.getAbsoluteFile()+""
+localFile.getFreeSpace());
}
}
运行结果如下:
‘陆’ java File读取和复制问题
importjava.io.File;
importjava.io.FileWriter;
importjava.io.IOException;
publicclassFileIO{
publicstaticvoidmain(String[]args){
Filefile=newFile("D:");
String[]fileList=file.list();
FilenewFile=newFile("D://1.txt");
FileWriterout=null;
try{
out=newFileWriter(newFile);
for(Stringstr:fileList){
out.write(str+" ");
}
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}finally{
if(out!=null)
try{
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
‘柒’ java中如何从文件中读取数据
1.package txt;
2.
3.import java.io.BufferedReader;
4.import java.io.File;
5.import java.io.FileInputStream;
6.import java.io.InputStreamReader;
7.
8./**
9. * 读取TXE数据
10. */
11.public class ReadTxtUtils {
12. public static void main(String arg[]) {
13. try {
14. String encoding = "GBK"; // 字符编码(可解决中文乱码问题 )
15. File file = new File("c:/aa.txt");
16. if (file.isFile() && file.exists()) {
17. InputStreamReader read = new InputStreamReader(
18. new FileInputStream(file), encoding);
19. BufferedReader bufferedReader = new BufferedReader(read);
20. String lineTXT = null;
21. while ((lineTXT = bufferedReader.readLine()) != null) {
22. System.out.println(lineTXT.toString().trim());
23. }
24. read.close();
25. }else{
26. System.out.println("找不到指定的文件!");
27. }
28. } catch (Exception e) {
29. System.out.println("读取文件内容操作出错");
30. e.printStackTrace();
31. }
32. }
33.}
java读取TXT文件中的数据,每一行就是一个数,返回一个数组,代码?
?
List list=new ArrayList();
BufferedReader br=new BufferReader(new InputStreamReader(new FileInputStream(new File("in.txt"))));
String str=null;
while((str=br.readLine())!=null)
{
list.add(new Integer(str));
}
Integer[] i=new Integer[list.size()];
list.toArray(i);
TXT文本中如据形如:
123
456
789
读入二维数组效果为:
temp[0][]={1,2,3};
temp[1][]={4,5,6};
temp[2][]={7,8,9};
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.*;
public class xx{
public static void main(String[]args){
String s;
int[][]save=new int[3][3];
try{
BufferedReader in =new BufferedReader(new FileReader("C:\\txt.txt"));
int i=0;
while((s=in.readLine())!=null){
save[i][0]=Integer.parseInt(s.substring(0,1));
save[i][1]=Integer.parseInt(s.substring(1,2));
save[i][2]=Integer.parseInt(s.substring(2,3));
i++;
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++){
System.out.print(save[i][j]);
}
System.out.println();
}
}
}
或
?
BufferedReader bf=new BufferedReader(new FileReader("Your file"));
String lineContent=null;
int i = 0;
int [][] temp = new int [3][];
while((lineContent=bf.readLine())!=null){
String [] str = lineContent.split("\\d");// 将 lineContent 按数字拆分
for(int j = 0; j < str.length(); j++){
int [i][j] = Integer.parseInt(str[j]);
}
i++;
}
scp|cs|ff|201101
这是d:\\a.txt的数据,与“|”分割取数据出来,保存在变量a;b;c;d里
import java.io.*;
public class Test{
public static void main(String[] args)throws Exception{
String a, b, c, d;
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new FileReader("d:\\a.txt"));
String s = br.readLine();
while(s != null){
sb.append(s);
s = br.readLine();
}
s = sb.toString();
String[] str = s.split("|");
a = str[0];
b = str[0];
c = str[0];
d = str[0];
}
}
‘捌’ java的几种IO流读取文件方式
一、超类:
字节流: InputStream(读入流) OutputStream(写出流)
字符流: Reader(字符 读入流) Writer (字符写出流)
二、文件操作流
字节流: FileInputStream ,FileOutputStream
字符流: FileReader, FileWriter(用法与字节流基本相同,不写)
//1.指定要读 的文件目录及名称
File file =new File("文件路径");
//2.创建文件读入流对象
FileInputStream fis =new FileInputStream(file);
//3.定义结束标志,可用字节数组读取
int i =0 ;
while((i = fis.read())!=-1){
//i 就是从文件中读取的字节,读完后返回-1
}
//4.关闭流
fis.close();
//5.处理异常
//1.指定要写到的文件目录及名称
File file =new File("文件路径");
//2.创建文件读入流对象
FileOutputStream fos =new FileOutputStream(file);
//3.定义结束标志
fos.write(要写出的字节或者字节数组);
//4.刷新和关闭流
fos.flush();
fos.close();
//5.处理异常
三、缓冲流:
字节缓冲流: BufferedInputStream,BufferedOutputStream
字符缓冲流:BufferedReader ,BufferedWriter
缓冲流是对流的操作的功能的加强,提高了数据的读写效率。既然缓冲流是对流的功能和读写效率的加强和提高,所以在创建缓冲流的对象时应该要传入要加强的流对象。
//1.指定要读 的文件目录及名称
File file =new File("文件路径");
//2.创建文件读入流对象
FileInputStream fis =new FileInputStream(file);
//3.创建缓冲流对象加强fis功能
BufferedInputStream bis =new BufferedInputStream(fis);
//4.定义结束标志,可用字节数组读取
int i =0 ;
while((i = bis.read())!=-1){
//i 就是从文件中读取的字节,读完后返回-1
}
//5.关闭流
bis.close();
//6.处理异常
//1.指定要写到的文件目录及名称
File file =new File("文件路径");
//2.创建文件读入流对象
FileOutputStream fos =new FileOutputStream(file);
//3.创建缓冲流对象加强fos功能
BufferedOutputStream bos=new BufferedOutputStream(fos);
//4.向流中写入数据
bos.write(要写出的字节或者字节数组);
//5.刷新和关闭流
bos.flush();
bos.close();
//6.处理异常
四、对象流
ObjectInputStream ,ObjectOutputStream
不同于以上两种类型的流这里只能用字节对对象进行操作原因可以看上篇的编码表比照原理
ObjectOutputStream对象的序列化:
将java程序中的对象写到本地磁盘里用ObjectOutputStream
eg:将Person类的对象序列化到磁盘
创建Person类
注1:此类要实现Serializable接口,此接口为标志性接口
注2:此类要有无参的构造函数
注3:一旦序列化此类不能再修改
class Person implements Serializable{
public Person(){}
}
2.创建对象流对象
注:要增强功能可以将传入文件缓冲流
ObjectOutputStream oos =new ObjectOutputStream(
new FileOutputStream(new File("文件路径")));
3.写入对象 ,一般会将对象用集合存储起来然后直接将集合写入文件
List<Person> list =new ArrayList<>();
list.add(new Person());
...(可以添加多个)
oos.writeObject(list);
4.关闭流,处理异常
oos.flush();
oos.close();
五、转换流:
这类流是用于将字符转换为字节输入输出,用于操作字符文件,属于字符流的子类,所以后缀为reader,writer;前缀inputstream,outputstream;
注 :要传入字节流作为参赛
InputStreamReader: 字符转换输出流
OutputStreamWriter:字符转换输入流
//1.获取键盘输入的字节流对象
inInputStream in =Stream.in;
/*2.用转换流将字节流对象转换为字符流对象,方便调用字符缓冲流的readeLine()方法*/
InputStreamReader isr =new InputStreamReader(in);
/*5.创建字符转换输出流对象osw,方便把输入的字符流转换为字节输出到本地文件。*/
OutputStreamWriter osw =new OutputStreamWriter(new
FileOutputStream(new File("文件名")));
/*3.现在isr是字符流,可以作为参数传入字符缓冲流中*/
BufferedReader br =new BufferedReader(isr);
/*4.可以调用字符缓冲流br的readLine()方法度一行输入文本*/
String line =null;
while((line =br.readLine()){
osw.write(line);//osw是字符流对象,可以直接操作字符串
}
注:InputStreamReader isr =new InputStreamReader(new "各种类型的字节输入流都行即是:后缀为InputStream就行");
OutputStreamWriter osw =new OutputStreamWriter(new
"后缀为OutputStream就行");
六、区别记忆
1.对象流是可以读写几乎所有类型的只要是对象就行,而字节字符流,只能读写单个字节字符或者字节字符数组,以上没有读写字节字符数组的;注意对象流只有字节流!
2.字符和字节循环读入的结束条件int i=0; (i =fis.read())!=-1
用字符数组复制文件(fr 读入流 ,fw写出流),字节流也是相同的用法
int i = 0; char[] c = new char[1024];
while((i = fr.reade()) !=-1)){
fw.write(c,0,i);
}
123456
3.对象流里面套缓冲流的情景:
new ObjectInputStream(new BufferedInputStream(new FileInputStream(new File(“文件路径”))));
4.记忆流及其功能的方法:
前缀表示功能,后缀表示流的类型;
比如说FileInputStream 前缀:File,表示操作的磁盘,后缀:intputstream,表示是字节输入流。
同理 FileReader:表示操作文件的字符流
ObjectInputStream :操作对象的字节输入流
5.拓展:获取键盘输入的字符的缓冲流的写法:
new BufferedReader(new InputStreamReader(System.in)));
将字节以字符形式输出到控制台的字符缓冲流的写法:
new BufferedWriter( new OutputStreamWriter(System.out))
‘玖’ 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);
}
}