导航:首页 > 编程语言 > filechanneljava

filechanneljava

发布时间:2022-04-19 00:43:02

java中怎样读取多个txt文件

java读取txt文件内容。可以作如下理解:
1.首先获得一个文件句柄。File file = new File(); file即为文件句柄。两人之间连通电话网络了。接下来可以开始打电话了。
2.通过这条线路读取甲方的信息:new FileInputStream(file) 目前这个信息已经读进来内存当中了。接下来需要解读成乙方可以理解的东西
3.既然你使用了FileInputStream()。那么对应的需要使用InputStreamReader()这个方法进行解读刚才装进来内存当中的数据
4.解读完成后要输出呀。那当然要转换成IO可以识别的数据呀。那就需要调用字节码读取的方法BufferedReader()。同时使用bufferedReader()的readline()方法读取txt文件中的每一行数据哈。
下面看个代码示例:
package com.campu;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
* @author 码农小江
* H20121012.java
* 2012-10-12下午11:40:21
*/
public class H20121012 {
/**
* 功能:Java读取txt文件的内容
* 步骤:1:先获得文件句柄
* 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
* 3:读取到输入流后,需要读取生成字节流
* 4:一行一行的输出。readline()。
* 备注:需要考虑的是异常情况
* @param filePath
*/
public static void readTxtFile(String filePath){
try {
String encoding="GBK";
File file=new File(filePath);
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
System.out.println(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}

}

public static void main(String argv[]){
String filePath = "L:\\Apache\\htdocs\\res\\20121012.txt";
// "res/";
readTxtFile(filePath);
}

}

❷ Java如何高效合并多个文件

import static java.lang.System.out;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;

public class test {
public static final int BUFSIZE = 1024 * 8;
public static void mergeFiles(String outFile, String[] files) {
FileChannel outChannel = null;
out.println("Merge " + Arrays.toString(files) + " into " + outFile);
try {
outChannel = new FileOutputStream(outFile).getChannel();
for(String f : files){
FileChannel fc = new FileInputStream(f).getChannel();
ByteBuffer bb = ByteBuffer.allocate(BUFSIZE);
while(fc.read(bb) != -1){
bb.flip();
outChannel.write(bb);
bb.clear();
}
fc.close();
}
out.println("Merged!! ");
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {if (outChannel != null) {outChannel.close();}} catch (IOException ignore) {}
}
}
public static void main(String[] args) {
mergeFiles("D:/output.txt", new String[]{"D:/in_1.txt", "D:/in_2.txt", "D:/in_3.txt"});
}
}

❸ java 如何读取大文件

以下将从常规方法谈起,通过对比来说明应该如何使用java读取大文件。

1、常规:在内存中读取
读取文件行的标准方式是在内存中读取,Guava 和Apache Commons IO都提供了如下所示快速读取文件行的方法:
Files.readLines(new File(path), Charsets.UTF_8);
FileUtils.readLines(new File(path));
这种方法带来的问题是文件的所有行都被存放在内存中,当文件足够大时很快就会导致程序抛出OutOfMemoryError 异常。
例如:读取一个大约1G的文件:
@Test
public void givenUsingGuava_whenIteratingAFile_thenWorks() throws IOException {
String path = ...
Files.readLines(new File(path), Charsets.UTF_8);
}
这种方式开始时只占用很少的内存:(大约消耗了0Mb内存)
然而,当文件全部读到内存中后,我们最后可以看到(大约消耗了2GB内存):
这意味这一过程大约耗费了2.1GB的内存——原因很简单:现在文件的所有行都被存储在内存中。
把文件所有的内容都放在内存中很快会耗尽可用内存——不论实际可用内存有多大,这点是显而易见的。
此外,我们通常不需要把文件的所有行一次性地放入内存中——相反,我们只需要遍历文件的每一行,然后做相应的处理,处理完之后把它扔掉。所以,这正是我们将要做的——通过行迭代,而不是把所有行都放在内存中。

2、文件流
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream(path);
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
// System.out.println(line);
}
// note that Scanner suppresses exceptions
if (sc.ioException() != null) {
throw sc.ioException();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
这种方案将会遍历文件中的所有行——允许对每一行进行处理,而不保持对它的引用。总之没有把它们存放在内存中:(大约消耗了150MB内存)

3、Apache Commons IO流
同样也可以使用Commons IO库实现,利用该库提供的自定义LineIterator:
LineIterator it = FileUtils.lineIterator(theFile, "UTF-8");
try {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
} finally {
LineIterator.closeQuietly(it);
}
由于整个文件不是全部存放在内存中,这也就导致相当保守的内存消耗:(大约消耗了150MB内存)

❹ java filechannel读取txt 乱码

乱码肯定是编码问题的原因,你首先检查下你生成的TXT是不是乱码,然后再检查读入后输出的是不是乱码,每个有关字符串编码的处理都可以用new String(otherString.getBytes("源编码集"),“目的编码集”);进行处理

❺ 利用java.nio的FileChannel能够实现按行读取文件吗(解决了)

利用java.nio的FileChannel能够实现按行读取文件:

具体思路是:设置两个缓冲区,一大一小,大的缓冲区为每次读取的量,小的缓冲区存放每行的数据(确保大小可存放文本中最长的那行)。读取的时候判断是不是换行符13,是的话则返回一行数据,不是的话继续读取,直到读完文件。

实现方法:

FileChannelfc=raf.getChannel();
//一次读取文件,读取的字节缓存数
ByteBufferfbb=ByteBuffer.allocate(1024*5);
fc.read(fbb);
fbb.flip();
//每行缓存的字节根据你的实际需求
ByteBufferbb=ByteBuffer.allocate(500);

//判断是否读完文件
publicbooleanhasNext()throwsIOException{

if(EOF)returnfalse;
if(fbb.position()==fbb.limit()){//判断当前位置是否到了缓冲区的限制
if(readByte()==0)returnfalse;
}
while(true){
if(fbb.position()==fbb.limit()){
if(readByte()==0)break;
}
bytea=fbb.get();
if(a==13){
if(fbb.position()==fbb.limit()){
if(readByte()==0)break;
}
returntrue;
}else{
if(bb.position()<bb.limit()){
bb.put(a);
}else{
if(readByte()==0)break;
}
}
}
returntrue;
}

❻ java filechannel 要关闭吗

输入输出流是要关闭的

❼ 如何通过FileChannel进行文件的读写操作

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo {

/**
* FileChannel是用于读取、写入、映射和操作文件的通道。
*
*文件通道在其文件中有一个当前 position,可对其进行查询和修改。
*该文件本身包含一个可读写的长度可变的字节序列,并且可以查询该文件的当前大小。
*写入的字节超出文件的当前大小时,则增加文件的大小;截取 该文件时,则减小文件的大小。
* @throws IOException
*/
public static void main(String[] args) throws IOException {
File in = new File("D:\\in.txt");
File out = new File("D:\\out.txt");
if(in.createNewFile()){
System.out.println("in.txt被创建");
FileOutputStream is = new FileOutputStream(in);
byte[] b = "我一定能行的".getBytes();
is.write(b, 0, b.length);
}
if(out.createNewFile()){
System.out.println("out.txt被创建");
}
FileInputStream is = new FileInputStream(in);
FileOutputStream os = new FileOutputStream(out);
FileChannel fis = is.getChannel();
FileChannel fos = os.getChannel();
ByteBuffer bytedata = ByteBuffer.allocate(100);
while(fis.read(bytedata)!= -1){
//通过通道读写交叉进行。
bytedata.flip();
fos.write(bytedata);
bytedata.clear();
}
fis.close();
fos.close();
is.close();
os.close();
}
}

❽ java中文件加锁机制是怎么实现的。

Java中文件加锁机制如下:
在对文件操作过程中,有时候需要对文件进行加锁操作,防止其他线程访问该文件。对文件的加锁方法有两种:
第一种方法:使用RandomAccessFile类操作文件。
在java.io.RandomAccessFile类的open方法,提供了参数实现独占的方式打开文件:
RandomAccessFile raf = new RandomAccessFile(file, "rws");
其中的“rws”参数,rw代表读取和写入,s代表了同步方式,也就是同步锁。这种方式打开的文件,就是独占方式的。

第二种方法:使用sun.nio.FileChannel对文件进行加锁。
代码:
RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
FileChannel fc = raf.getChannel();
FileLock fl = fc.tryLock();
if(fl.isValid())
System.out.println("You have got the file lock.");

以上是通过RandomAccessFile来获得文件锁的,方法如下:
代码:
FileOutputStream fos = new FileOutputStream("file.txt");
FileChannel fc = fos.getChannel(); //获取FileChannel对象
FileLock fl = fc.tryLock(); //or fc.lock();
if(null != fl)
System.out.println("You have got file lock.");
//TODO write content to file
//TODO write end, should release this lock
fl.release(); //释放文件锁
fos.close; //关闭文件写操作

如果在读文件操作的时候,对文件进行加锁,操作过程如下:
FileChannel也可以从FileInputStream中直接获得,但是这种直接获得FileChannel的对象直接去操作FileLock会报异常NonWritableChannelException,需要自己去实现getChannel方法,代码如下:
private static FileChannel getChannel(FileInputStream fin, FileDescriptor fd) {
FileChannel channel = null;
synchronized(fin){
channel = FileChannelImpl.open(fd, true, true, fin);
return channel;
}
}

其实,看FileInputStream时,发现getChannel方法与我们写的代码只有一个地方不同,即open方法的第三个参数不同,如果设置为false,就不能锁住文件了。缺省的getChannel方法,就是false,因此,不能锁住文件。

❾ java编程完成下列功能:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;

public class Test{
public static void main(String[] args) throws Exception {
//创建2个文件
File file1 = new File("D://test1.txt");
File file2 = new File("d://test2.txt");
file1.createNewFile();
file2.createNewFile();

//从键盘输入的字符写入test1.txt
FileWriter fout = new FileWriter(file1);
String str=null;
System.out.println("Please input a String:");
BufferedReader fin = new BufferedReader(new InputStreamReader(System.in));
str = fin.readLine();
System.out.println(str);
fout.write(str,0,str.length());
fout.flush();
fout.close();
fin.close();

//复制文件test1.txt的内容到test2.txt
//为了让你明白通道所以我这里用了2种读写入文件的方法
new Exam2().("D://test1.txt", "d://test2.txt");

}
/**
* 复制文件封装类
* @param url1
* @param url2
* @throws Exception
*/
public void (String url1, String url2) throws Exception {
FileInputStream input = new FileInputStream(url1);
FileChannel filechannel = input.getChannel();
FileOutputStream output = new FileOutputStream(url2);
FileChannel filechannel2 = output.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024 * 8);
while (filechannel.read(buf) != -1) {
buf.flip();
filechannel2.write(buf);
buf.clear();
}
input.close();
filechannel.close();
output.close();
filechannel2.close();
}
}

您的进步是我最大的动力,如果你觉得我回答的合理的话,请给我多加分。谢谢,如果不明白的话,请给我留言。大家相互学习啊! 加油!

阅读全文

与filechanneljava相关的资料

热点内容
php如何选中相同的进行修改 浏览:623
工行app个人怎么给企业账户转账 浏览:149
汇编与程序员 浏览:666
压缩包解码器下载 浏览:130
爱旅行的预备程序员 浏览:111
安卓qq浏览器怎么转换到ios 浏览:292
不同编译器的库可以调用吗 浏览:455
灰度信托基金加密 浏览:421
宿迁程序员兼职网上接单 浏览:924
电视编译器怎么设置 浏览:276
手机如何解压汉字密码的压缩包 浏览:701
为什么很多程序员爱用vim 浏览:828
安卓手机怎么连接宝华韦健音响 浏览:555
12星座制作解压球 浏览:867
java调用oracle数据 浏览:827
怎么在服务器上上传小程序源码 浏览:304
空中加油通达信指标公式源码 浏览:38
分卷解压只解压了一部分 浏览:760
php网站自动登录 浏览:705
合肥凌达压缩机招聘 浏览:965