新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

java读流写流代码 java输入输出流代码

java输入输出流与文件,求源代码!感谢大佬!

你好,java的API中提供了用于对象输入输出文件的操作,实例代码如下:

成都创新互联长期为近千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为九龙坡企业提供专业的成都网站建设、成都网站制作,九龙坡网站改版等技术服务。拥有10多年丰富建站经验和众多成功案例,为您定制开发。

定义单词类如下(注意:你定义的类要实现Serializable接口)

public class Words implements Serializable {

private int size;

private String[] words;

public Words(){};

public Words(String...strs){

this.words = strs;

this.size = strs.length;

}

@Override

public String toString() {

return "Words{" +

"size=" + size +

", words=" + Arrays.toString(words) +

'}';

}

}

2. 对象输入输出api测试类

public class ObjIOTest {

public static void main(String[] args) {

String path = "d:/myIOTest.txt";

ObjIOTest objIOTest = new ObjIOTest();

Words words = new Words("hello", "my", "dear", "friend");

try {

objIOTest.writeObject(path,words);

Words wordsFromFile = (Words)objIOTest.readObject(path);

System.out.println(wordsFromFile.toString());

} catch (IOException | ClassNotFoundException e) {

e.printStackTrace();

}

}

//java serialize a object to file

public void writeObject(String path,Object map) throws IOException{

File f=new File(path);

FileOutputStream out=new FileOutputStream(f);

ObjectOutputStream objwrite=new ObjectOutputStream(out);

objwrite.writeObject(map);

objwrite.flush();

objwrite.close();

}

// read the object from the file

public Object readObject(String path) throws IOException, ClassNotFoundException{

FileInputStream in=new FileInputStream(path);

ObjectInputStream objread=new ObjectInputStream(in);

Object map=objread.readObject();

objread.close();

return map;

}

}

把两段代码拷贝到一个包下即可运行了,希望您的问题得到解答

java 文件读写流

首先你要知道java的io流主要分两种,一种是字符流,另一种字节流,还有一种过滤流,这个不常用,暂且可以忽略。

等你这些都掌握了,推荐你用nio包中的管道流。

流的套用可以提升读写效率(这种方式只能是同类流的套用,比如字节流套用字节流),还有一种是字符流与字节流互相转换,转换通过一种叫做“桥转换”的类,比如OutputStreamWriter类。

下面举个最基础的字节流例子:

public void copyFile(String file, String bak) {

BufferedInputStream bis = null;

BufferedOutputStream bos = null;

try {

byte[] bytes = new byte[1024];

bis = new BufferedInputStream(new FileInputStream(file));//BufferedInputStream会构造一个背部缓冲区数组,将FileInputStream中的数据存放在缓冲区中,提升了读取的性能

bos = new BufferedOutputStream(new FileOutputStream(bak));//同理

int length = bis.read(bytes);

while (length != -1) {

System.out.println("length: " + length);

bos.write(bytes, 0, length);

length = bis.read(bytes);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

bis.close();

bos.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

字符流的用法:

FileReader fr = new FileReader("D:\\test.txt");

BufferedReader br = new BufferedReader(fr);

或者PrintWriter pw = new PrintWriter(new FileWriter("D:\\test.txt"));

...

java 中简述使用流进行读写文本文件的步骤?

一、Java IO学习基础之读写文本文件

Java的IO操作都是基于流进行操作的,为了提高读写效率一般需要进行缓冲。

简单的示例程序如下:

/**

* 读出1.txt中的内容,写入2.txt中

*

*/

import java.io.*;

public class ReadWriteFile{

public static void main(String[] args){

try{

File read = new File("c:\\1.txt");

File write = new File("c:\\2.txt");

BufferedReader br = new BufferedReader(

new FileReader(read));

BufferedWriter bw = new BufferedWriter(

new FileWriter(write));

String temp = null;

temp = br.readLine();

while(temp != null){

//写文件

bw.write(temp + "\r\n"); //只适用Windows系统

//继续读文件

temp = br.readLine();

}

bw.close();

br.close();

}catch(FileNotFoundException e){ //文件未找到

System.out.println (e);

}catch(IOException e){

System.out.println (e);

}

}

}

以上是一个比较简单的基础示例。本文上下两部分都是从网上摘抄,合并在一起,方便下自己以后查找。

二、Java IO学习笔记+代码

文件对象的生成和文件的创建

/*

* ProcessFileName.java

*

* Created on 2006年8月22日, 下午3:10

*

* 文件对象的生成和文件的创建

*/

package study.iostudy;

import java.io.*;

public class GenerateFile

{

public static void main(String[] args)

{

File dirObject = new File("d:\\mydir");

File fileObject1 = new File("oneFirst.txt");

File fileObject2 = new File("d:\\mydir", "firstFile.txt");

System.out.println(fileObject2);

try

{

dirObject.mkdir();

}catch(SecurityException e)

{

e.printStackTrace();

}

try

{

fileObject2.createNewFile();

fileObject1.createNewFile();

}catch(IOException e)

{

e.printStackTrace();

}

}

}

文件名的处理

/*

* ProcessFileName.java

*

* Created on 2006年8月22日, 下午3:29

*

* 文件名的处理

*/

package study.iostudy;

import java.io.*;

/*

* 文件名的处理

* String getName(); 获得文件的名称,不包含文件所在的路径。

* String getPath(); 获得文件的路径。

* String getAbsolutePath(); 获得文件的绝对路径。

* String getParent(); 获得文件的上一级目录的名称。

* String renameTo(File newName); 按参数中给定的完整路径更改当前的文件名。

* int compareTo(File pathName); 按照字典顺序比较两个文件对象的路径。

* boolean isAbsolute(); 测试文件对象的路径是不是绝对路径。

*/

public class ProcesserFileName

{

public static void main(String[] args)

{

File fileObject1 = new File("d:\\mydir\\firstFile.txt");

File fileObject2 = new File("d:\\firstFile.txt");

boolean pathAbsolute = fileObject1.isAbsolute();

System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");

System.out.println("There are some information of fileObject1's file name:");

System.out.println("fileObject1: " + fileObject1);

System.out.println("fileObject2: " + fileObject2);

System.out.println("file name: " + fileObject1.getName());

System.out.println("file path: " + fileObject1.getPath());

System.out.println("file absolute path: " + fileObject1.getAbsolutePath());

System.out.println("file's parent directory: " + fileObject1.getParent());

System.out.println("file's absoulte path: " + pathAbsolute);

int sameName = fileObject1.compareTo(fileObject2);

System.out.println("fileObject1 compare to fileObject2: " + sameName);

fileObject1.renameTo(fileObject2);

System.out.println("file's new name: " + fileObject1.getName());

}

}

测试和设置文件属性

/*

* SetterFileAttribute.java

*

* Created on 2006年8月22日, 下午3:51

*

* 测试和设置文件属性

*/

package study.iostudy;

import java.io.*;

public class SetterFileAttribute

{

/*

* File类中提供的有关文件属性测试方面的方法有以下几种:

* boolean exists(); 测试当前文件对象指示的文件是否存在。

* boolean isFile(); 测试当前文件对象是不是文件。

* boolean isDirectory(); 测试当前文件对象是不是目录。

* boolean canRead(); 测试当前文件对象是否可读。

* boolean canWrite(); 测试当前文件对象是否可写。

* boolean setReadOnly(); 将当前文件对象设置为只读。

* long length(); 获得当前文件对象的长度。

*/

public static void main(String[] args)

{

File dirObject = new File("d:\\mydir");

File fileObject = new File("d:\\mydir\\firstFile.txt");

try

{

dirObject.mkdir();

fileObject.createNewFile();

}catch(IOException e)

{

e.printStackTrace();

}

System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");

System.out.println("there are some information about property of file object:");

System.out.println("file object : " + fileObject);

System.out.println("file exist? " + fileObject.exists());

System.out.println("Is a file? " + fileObject.isFile());

System.out.println("Is a directory?" + fileObject.isDirectory());

System.out.println("Can read this file? " + fileObject.canRead());

System.out.println("Can write this fie? " + fileObject.canWrite());

long fileLen = fileObject.length();

System.out.println("file length: " +fileLen);

boolean fileRead = fileObject.setReadOnly();

System.out.println(fileRead);

System.out.println("Can read this file? " + fileObject.canRead());

System.out.println("Can write this fie? " + fileObject.canWrite());

System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");

}

}

文件操作方法

/*

* FileOperation.java

*

* Created on 2006年8月22日, 下午4:25

*

* 文件操作方法

*/

package study.iostudy;

import java.io.*;

/*

* 有关文件操作方面的方法有如下几种:

* boolean createNewFile(); 根据当前的文件对象创建一个新的文件。

* boolean mkdir(); 根据当前的文件对象生成一目录,也就是指定路径下的文件夹。

* boolean mkdirs(); 也是根据当前的文件对象生成一个目录,

* 不同的地方在于该方法即使创建目录失败,

* 也会成功参数中指定的所有父目录。

* boolean delete(); 删除当前的文件。

* void deleteOnExit(); 当前Java虚拟机终止时删除当前的文件。

* String list(); 列出当前目录下的文件。

*/

public class FileOperation

* 找出一个目录下所有的文件

package study.iostudy;

import java.io.*;

public class SearchFile

{

public static void main(String[] args)

{

File dirObject = new File("D:\\aa");

Filter1 filterObj1 = new Filter1("HTML");

Filter2 filterObj2 = new Filter2("Applet");

System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

System.out.println("list HTML files in directory: " + dirObject);

String[] filesObj1 = dirObject.list(filterObj1);

for (int i = 0; i filesObj1.length; i++)

{

File fileObject = new File(dirObject, filesObj1[i]);

System.out.println(((fileObject.isFile())

? "HTML file: " : "sub directory: ") + fileObject);

}

System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

String[] filesObj2 = dirObject.list(filterObj2);

for (int i = 0; i filesObj2.length; i++)

{

File fileObject = new File(dirObject, filesObj2[i]);

System.out.println(((fileObject.isFile())

? "htm file: " : "sub directory: ") + fileObject);

}

}

}

class Filter1 implements FilenameFilter

{

String fileExtent;

Filter1(String extentObj)

{

fileExtent = extentObj;

}

public boolean accept(File dir, String name)

{

return name.endsWith("." + fileExtent);

}

}

class Filter2 implements FilenameFilter

{

String fileName;

Filter2(String fileName)

{

this.fileName = fileName;

字符流处理

* ProcesserCharacterStream.java

* 字符流处理

*

* java.io包中加入了专门用于字符流处理的类,这些类都是Reader和Writer类的子类,

* Reader和Writer是两个抽象类,只提供了一系列用于字符流处理的接口,不能生成这

* 两个类的实例。

* java.io包中用于字符流处理的最基本的类是InputStreamReader和OutputStreamWriter,

* 用来在字节流和字符流之间作为中介。

*

* 下面是InputStreamReader类和OutputStreamWriter类的常用方法:

*

* public InputStreamReader(InputStream in)

* 根据当前平台缺省的编码规范,基于字节流in生成一个输入字符流。

* public InputStreamReader(InputStream in, String sysCode)throws UnSupportedEncodingException

* 按照参数sysCode指定的编码规范,基于字节流in构造输入字符流,如果不支持参数sysCode中指定的编码规范,就会产生异常。

* public OutputStreamWriter(OutputStream out)

* 根据当前平台缺省的编码规范,基于字节流out生成一个输入字符流。

* public OutputStreamWriter(OutputStream out, String sysCode) throws UnsupportedEncodingException

* 按照参数sysCode指定的编码规范,基于字节流out构造输入字符流,如果不支持参数sysCode中指定的编码规范,就会产生异常。

* public String getEncoding()

* 获得当前字符流使用的编码方式。

* public void close() throws IOException

* 用于关闭流。

* public int read() throws IOException

* 用于读取一个字符。

* public int read(char[] cbuf, int off, int len)

* 用于读取len个字符到数组cbuf的索引off处。

* public void write(char[] cbuf, int off, int len) throws IOException

* 将字符数组cbuf中从索引off处开始的len个字符写入输出流。

* public void write(int c) throws IOException

* 将单个字符写入输入流。

* public void write(String str, int off, int len) throws IOException

* 将字符串str中从索引off位置开始的ltn个字符写入输出流。

*

* 此外,为了提高字符流处理的效率,在Java语言中,引入了BufferedReader和BufferWriter类,这两个类对字符流进行块处理。

* 两个类的常用方法如下:

* public BufferedReader(Reader in)

* 用于基于普通字符输入流in生成相应的缓冲流。

* public BufferedReader(Reader in, int bufSize)

* 用于基于普通字符输入流in生成相应的缓冲流,缓冲区大小为参数bufSize指定。

* public BufferedWriter(Writer out)

* 用于基于普通字符输入流out生成相应的缓冲流。

* public BufferedWriter(Writer out, int bufSize)

* 用于基于普通字符输入流out生在相应缓冲流,缓冲流大小为参数bufSize指定。

* public String readLine() throws IOException

* 用于从输入流中读取一行字符。

* public void newLine() throws IOException

* 用于向字符输入流中写入一行结束标记,值得注意的是,该标记不是简单的换行符"\n",而是系统定义的属性line.separator。

在上面的程序中,我们首先声明了FileInputStream类对象inStream和

* FileOutputStream类的对象outStream,接着声明了BufferInputStream

* 类对象bufObj、BufferedOutputStream类对象bufOutObj、

* DataInputStream类对象dataInObj以及PushbackInputStream类对象pushObj,

* 在try代码块中对上面这些对象进行初始化,程序的目的是通过BufferedInputStream

* 类对象bufInObj和BufferedOutputStream类对象bufOutObj将secondFile.txt

* 文件中内容输出到屏幕,并将该文件的内容写入thirdFile.txt文件中,值得注意的是,

* 将secondFile.txt文件中的内容输出之前,程序中使用

* "System.out.println(dataInObj.readBoolean());" 语句根据readBoolean()结果

* 输出了true,而secondFile.txt文件开始内容为“Modify”,和一个字符为M,

* 因此输出的文件内容没有“M”字符,thirdFile.txt文件中也比secondFile.txt

* 文件少第一个字符“M”。随后,通过PushbackInputStream类对象pushObj读取

* thirdFile.txt文件中的内容,输出读到的字符,当读到的不是字符,输出回车,将字符

* 数组pushByte写回到thirdFile.txt文件中,也就是“ok”写回文件中。

* 对象串行化

* 对象通过写出描述自己状态的数值来记录自己,这个过程叫做对象串行化。对象的寿命通

* 常是随着生成该对象的程序的终止而终止,在有些情况下,需要将对象的状态保存下来,然后

* 在必要的时候将对象恢复,值得注意的是,如果变量是另一个对象的引用,则引用的对象也要

* 串行化,串行化是一个递归的过程,可能会涉及到一个复杂树结构的串行化,比如包括原有对

* 象,对象的对象等。

* 在java.io包中,接口Serializable是实现对象串行化的工具,只有实现了Serializable

* 的对象才可以被串行化。Serializable接口中没有任何的方法,当一个类声明实现Seriali-

* zable接口时,只是表明该类遵循串行化协议,而不需要实现任何特殊的方法。

* 在进行对象串行化时,需要注意将串行化的对象和输入、输出流联系起来,首先通过对

* 象输出流将对象状态保存下来,然后通过对象输入流将对象状态恢复。

用java分别以字节流和文本流方式实现文件的读写操作(先向test1.txt文件中写“各位同学:

import java.io.File;

import java.io.IOException;

import java.io.FileOutputStream;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

public class StreamTest {

public static void main(String[] args) {

StreamTest st = new StreamTest();

String writeStr = "Hello World!\r\n你好!";

String fileName = "outFile.txt";

st.OutputTest(fileName,writeStr);

st.InputTest(fileName);

}

//字节-读

private void InputTest(String fileName) {

File f = createFile(fileName);

FileInputStream fis;

byte[] b = new byte[100];

try {

System.out.println("创建输入流...");

fis = new FileInputStream(f);

System.out.println("创建输入流完成");

System.out.println("开始读取...");

fis.read(b);

System.out.println("读取完成");

String str = new String(b);

System.out.println("读取内容输出:\n"+str);

fis.close();

}catch(FileNotFoundException e) {

System.out.println("文件没有找到");

}catch(IOException e) {

System.out.println("读取失败");

}

}

//字节-写

private void OutputTest(String fileName,String text) {

File f = createFile(fileName);

FileOutputStream fos;

try{

System.out.println("创建输出流...");

fos = new FileOutputStream(f);

System.out.println("创建输出流完成");

byte[] testBArray = text.getBytes();

System.out.println("开始写数据...");

fos.write(testBArray);

fos.flush();

System.out.println("写数据完成");

fos.close();

}catch(FileNotFoundException e) {

System.out.println("文件没有找到");

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}

}

//创建文件

private File createFile(String fileName) {

File f = new File(fileName);

if(!f.exists()) {

System.out.println("文件不存在");

try{

System.out.println("创建文件...");

f.createNewFile();

System.out.println("创建文件完成");

}catch(IOException e) {

System.out.println("文件创建失败");

e.printStackTrace();

}

}else {

System.out.println("文件已经存在");

}

return f;

}

}

字符流的话改成FileWriter(),FileReader()就好啦!

不懂加:百度HI!^0^

跪求Java中写入文件和从文件中读取数据的最佳的代码!

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

public class IOTest {

public static void main(String[] args) {

String str = "123\r\n456";

writeFile(str);//写

String str1 = readFile();//读

System.out.println(str1);

}

/**

* 传递写的内容

* @param str

*/

static void writeFile(String str) {

try {

File file = new File("d:\\file.txt");

if(file.exists()){//存在

file.delete();//删除再建

file.createNewFile();

}else{

file.createNewFile();//不存在直接创建

}

FileWriter fw = new FileWriter(file);//文件写IO

fw.write(str);

fw.flush();

fw.close();

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 返回读取的内容

* @return

*/

static String readFile() {

String str = "", temp = null;

try {

File file = new File("d:\\file.txt");

FileReader fr = new FileReader(file);

BufferedReader br = new BufferedReader(fr);//文件读IO

while((temp = br.readLine())!=null){//读到结束为止

str += (temp+"\n");

}

br.close();

fr.close();

} catch (IOException e) {

e.printStackTrace();

}

return str;

}

}

刚写的,够朋友好好学习一下啦,呵呵

多多看API,多多练习


分享题目:java读流写流代码 java输入输出流代码
链接URL:http://www.wjwzjz.com/article/hjciih.html
在线咨询
服务热线
服务热线:028-86922220
TOP