java读取TXT文件

java读取TXT文件
java读取TXT文件

1、按字节读取文件内容

2、按字符读取文件内容

3、按行读取文件内容

4、随机读取文件内容

5、将内容追加到文件尾部

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);

}

}

public class AppendToFile {

/**

* A方法追加文件:使用RandomAccessFile

*/

public static void appendMethodA(String fileName, String content) {

try {

// 打开一个随机访问文件流,按读写方式

RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw"); // 文件长度,字节数

long fileLength = randomFile.length();

//将写文件指针移到文件尾。

randomFile.seek(fileLength);

randomFile.writeBytes(content);

randomFile.close();

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* B方法追加文件:使用FileWriter

*/

public static void appendMethodB(String fileName, String content) {

try {

//打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件

FileWriter writer = new FileWriter(fileName, true);

writer.write(content);

writer.close();

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

String fileName = "C:/temp/newTemp.txt";

String content = "new append!";

//按方法A追加文件

AppendToFile.appendMethodA(fileName, content);

AppendToFile.appendMethodA(fileName, "append end. \n"); //显示文件内容

ReadFromFile.readFileByLines(fileName);

//按方法B追加文件

AppendToFile.appendMethodB(fileName, content);

AppendToFile.appendMethodB(fileName, "append end. \n"); //显示文件内容

ReadFromFile.readFileByLines(fileName);

}

}

java文件流操作

java 文件流操作 2010-05-08 20:17:23| 分类:java SE | 标签:|字号大中小订阅 java中多种方式读文件 一、多种方式读文件内容。 1、按字节读取文件内容InputStream 读取的是字节 2、按字符读取文件内容InputStreamReader 读取的是字符 3、按行读取文件内容BufferredReader 可以读取行 4、随机读取文件内容 import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.io.Reader; public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。* @param fileName 文件的名 */ 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("以字节为单位读取文件内容,一次读多个字节:"); //一次读多个字节

java创建txt文件并进行读写修改操作

java创建txt文件并进行读写修改操作 import java.io.*;/** * * 功能描述:创建TXT文件并进行读、写、修改操作* */ public class ReadWriteFile { public static BufferedReader bufread; //指定文件路径和名称 private static String path = "D:/suncity.txt"; private static File filename = new File(path); private static String readStr =""; /** * 创建文本文件. * @throws IOException * */ public static void creatTxtFile() throws IOException{ if (!filename.exists()) { filename.createNewFile(); System.err.println(filename + "已创建!"); }

} /** * 读取文本文件. * */ public static String readTxtFile(){ String read; FileReader fileread; try { fileread = new FileReader(filename); bufread = new BufferedReader(fileread); try { while ((read = bufread.readLine()) != null) { readStr = readStr + read+ "\r\n"; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block

Java读取txt文件中指定行内容

获取文本内容与读取文本指定行数内容浅析(java) 在此项目中直接套用以前工程中获取文本内容的方法发现一直提示“数组下标越界”,通过分析和查找得出以下心得: 获取文本内容: private static final String CHART_PATH ="D://data3"; public static void main(String[] args) throws RowsExceededException,WriteException, BiffException{ try { readFileByLines(CHART_PATH+".txt"); } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } } public static void readFileByLines(String fileName) throws IOException,RowsExceededException,WriteException{ //打开文件 WritableWorkbook book = Workbook.createWorkbook( new File(CHART_PATH+".xls")); WritableSheet sheet = book.createSheet("看我", 0); //读取txt文件内容 File file = new File(fileName); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis,"GBK"); BufferedReader reader = null; try { reader = new BufferedReader(isr); String temString = null; //一次读入一行,以null结束 int i = 0; while((temString = reader.readLine())!= null){ System.out.println("+++++++"+temString); String[] str = temString.split(","); for(int j= 0;j

java对文件名的几个操作,获取文件扩展名,去掉扩展名

java对文件名的几个操作,获取文件扩展名,去掉扩展名 /** * Return the extension portion of the file's name . * * @see #getExtension */ public static String getExtension(File f) { return (f != null) ? getExtension(f.getName()) : ""; } public static String getExtension(String filename) { return getExtension(filename, ""); } public static String getExtension(String filename) { return getExtension(filename, ""); } public static String getExtension(String filename, String defExt) { if ((filename != null) && (filename.length() > 0)) { int i = https://www.360docs.net/doc/eb12653043.html,stIndexOf('.'); if ((i >-1) && (i < (filename.length() - 1))) { return filename.substring(i + 1); } } return defExt; } public static String trimExtension(String filename) { if ((filename != null) && (filename.length() > 0)) { int i = https://www.360docs.net/doc/eb12653043.html,stIndexOf('.'); if ((i >-1) && (i < (filename.length()))) { return filename.substring(0, i); } } return filename; } substring(参数)是java中截取字符串的一个方法 有两种传参方式

Java 输入输出流及文件读写详解

I/O类体系 在JDK API中,基础的IO类都位于java.io包,而新实现的IO类则位于一系列以java.nio开头的包名中,这里首先介绍java.io包中类的体系结构。 按照前面的说明,流是有方向的,则整个流的结构按照流的方向可以划分为两类: 1、输入流: 该类流将外部数据源的数据转换为流,程序通过读取该类流中的数据,完成对于外部数据源中数据的读入。 2、输出流: 该类流完成将流中的数据转换到对应的数据源中,程序通过向该类流中写入数据,完成将数据写入到对应的外部数据源中。 而在实际实现时,由于JDK API历史的原因,在java.io包中又实现了两类流:字节流(byte stream)和字符流(char stream)。这两种流实现的是流中数据序列的单位,在字节流中,数据序列以byte为单位,也就是流中的数据按照一个byte一个byte的顺序实现成流,对于该类流操作的基本单位是一个byte,而对于字节流,数据序列以char为单位,也就是流中的数据按照一个char一个插入的顺序实现成流,对于该类流操作的基本单位是一个char。 另外字节流是从JDK1.0开始加入到API中的,而字符流则是从JDK1.1开始才加入到API中的,对于现在使用的JDK版本来说,这两类流都包含在API的内部。在实际使用时,字符流的效率要比字节流高一些。 在实际使用时,字符流中的类基本上和字节流中的类对应,所以在开始学习IO类时,可以从最基础的字节流开始学习。 在SUN设计JDK的IO类时,按照以上的分类,为每个系列的类设计了一个父类,而实现具体操作的类都作为该系列类的子类,则IO类设计时的四个体系中每个体系中对应的父类分别是: 字节输入流InputStream 该类是IO编程中所有字节输入流的父类,熟悉该类的使用将对使用字节输入流产生很大的帮助,下面做一下详细的介绍。 按照前面介绍的流的概念,字节输入流完成的是按照字节形式构造读取数据的输入流的结构,每个该类的对象就是一个实际的输入流,在构造时由API完成将外部数据源转换为流对象的操作,这种转换对程序员来说是透明的。在程序使用时,程序员只需要读取该流对象,就可以完成对于外部数据的读取了。

java读取上传excel文件和txt文件中的数据

Java 读取上传文件里的数据,记事本文件和excel文件 本文,文本文件里的数据,每列以 Tab 分隔。 其它分隔符情况下,只需修改对分隔符的判断即可 本文是将文本文件或excel文件里的数据读到List 里。 List , List, ........可以改为返回其它类型的数据集 UpLoadExcel 类里需要操作excel的 jar包 import org.apache.poi.* ; 网上可以搜索下载,简单快捷 ---------------------------------------------------------------------------- - - - public class upLoadAction extends DispatchAction { public ActionForward doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { TestForm myForm = (TestForm) form; FormFile f = myForm.getUpfisle(); //get上传文件 String fileName = f.getFileName(); // 截取文件名的后三位字符 String fileType = fileName.substring(fileName.length()-3,fileName.length()); System.out.println("导入的文件名:"+fileName+"\t 文件后缀名:"+fileType); List list = new ArrayList(); if("xls".equals(fileType)){ // 上传文件是excel时文件文件后缀名为xls list = new UpLoadExcel().getExcelData(f.getInputStream()); }else if("txt".equals(fileType)){ list = new UploadText().UploadText(f.getInputStream()); } // 操作读取出来的数据,例如: if (list.size() > 0) { String[] str = null; for(int i = 0; i < list.size(); i++) { str = list.get(i); st = "insert into student (sName,sAge,sAddress,sTelephone) values(" ; st = "'" + st + str[0] + "'"; st = ",'" + st + str[1] + "'"; st = ",'" + st + str[4] + "'"; st = ",'" + st + str[6] + "'"; st = st + ")"; ...... System.out.println(st);

Java读取Excel文件的几种方法

Java读取Excel文件的几种方法 最近单位有个项目需要读取excel文件的内容,特别对java读取excel文件的方法做了一点学习,也为了其他人以后能更简单地开发,少走弯路,特写此文,以下程序经过了我的测试,可以保证程序可用,如果你照搬都不行,可能是你的环境有问题。 读取excel文件的常用开源免费方法有以下几种: JDBC-ODBC Excel Driver jxl.jar jcom.jar poi.jar 下面分别对这几种方法分别进行探讨 1、JDBC-ODBC Excel Driver 这种方法是将excel看成是数据库进行操作,使用SQL Select语句即可 查询excel表格。优点是:不需要第三方的jar包。 如下表样 首先在控制面板进行数据源ODBC登记 具体方法如下:

下面就是代码了。 package xuzhe;

import java.io.*; import java.sql.*; //java xuzhe.ExcelJDBC public class ExcelJDBC { public static void main(String[] args) throws SQLException{ Connection con = null; try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection( "jdbc:odbc:ExcelJDBC" ); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "Select * from [Sheet1$]" ); ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); System.out.println ("表格列数"+numberOfColumns ); System.out.println( rsmd.getColumnName(1)+ "," + rsmd.getColumnName(2) + "," + rsmd.getColumnName(3)); while (rs.next()) { for (int i = 1; i <= numberOfColumns; i++) { if (i > 1) System.out.print(", "); String columnValue = rs.getString(i); System.out.print(columnValue); } System.out.println(""); } rs.close(); st.close(); } catch(Exception ex) { System.err.print("Exception: "); System.err.println(ex.getMessage()); } finally { con.close(); } } } 执行结果如下:

java文件读写代码

1、按字节读取文件内容 2、按字符读取文件内容 3、按行读取文件内容 4、随机读取文件内容 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); }

java读写文件避免中文乱码

1、JAVA读取文件,避免中文乱码。 /** * 读取文件内容 * * @param filePathAndName * String 如c:\\1.txt 绝对路径 * @return boolean */ public static String readFile(String filePathAndName) { String fileContent = ""; try { File f = new File(filePathAndName); if(f.isFile()&&f.exists()){ InputStreamReader read = new InputStreamReader(new FileInputStream(f),"UTF-8"); BufferedReader reader=new BufferedReader(read); String line; while ((line = reader.readLine()) != null) { fileContent += line; } read.close(); } } catch (Exception e) { System.out.println("读取文件内容操作出错"); e.printStackTrace(); } return fileContent; } 2、JAVA写入文件,避免中文乱码。 public static void writeFile(String filePathAndName, String fileContent) { try { File f = new File(filePathAndName); if (!f.exists()) { f.createNewFile(); } OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"UTF-8"); BufferedWriter writer=new BufferedWriter(write); //PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName))); //PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName)); writer.write(fileContent);

Java流(文件读写操作)

Java流 一、流的分类 ?按数据流动方向 –输入流:只能从中读取字节数据,而不能向其写出数据 –输出流:只能向其写入字节数据,而不能从中读取数据?按照流所处理的数据类型 –字节流:用于处理字节数据。 –字符流:用于处理Unicode字符数据。 ?按照流所处理的源 –节点流:从/向一个特定的IO设备读/写数据的流。(低级流)–处理流:对已存在的流进行连接和封装的流。(高级流)二、缓冲流 ?缓冲流要“套接”在相应的节点流之上,对读写的数据提供了缓冲的功能,提高了读写的效率,同时增加了一些新的方法。 ?J2SDK提供了四种缓存流: –BufferedReader –BufferedWriter –BufferedInputStream s –BufferedOutputStream

?缓冲输入流支持其父类的mark()和reset()方法: –mark()用于“标记”当前位置,就像加入了一个书签,可以使用reset()方法返回这个标记重新读取数据。?BufferedReader提供了readLine()方法用于读取一行字符串(以\r 或\n分隔)。 ?BufferedWriter提供了newLine()用于写入一个行分隔符。 ?对于输出的缓冲流,写出的数据会先在内存中缓存,使用flush()方法将会使内存中的数据立刻写出。 三、类层次 3.1、InputStream类层次

3.2、OutputStream类层次 3.3、Reader类层次

3.4、Writer类层次 四、常用的字符流与字节流的转化 说明: 1.字节流用于读写诸如图像数据之类的原始字节流。 2.字符流用于读写诸如文件数据之类的字符流。 3.低级流能和外设交流。 4.高级流能提高效率。 5.InputStreamReader 是字节流通向字符流的桥梁。 6.OutputStreamWriter 是字符流通向字节流的桥梁。

java File文件操作和文件流的详解(福哥出品)

一. 创建文件 (1)最常用的(获得一个固定路径下的文件对象) File parentFile = new File(“D:\\My Documents\\.....”);//参数是一个路径的字符串。 (2)在父目录创建一个名为child的文件对象,child 为文件对象的名字 File chileFile= new File(“D:\\My Documents\\.....”,String child); 或File chileFile= new File(parentFile,String child); 二,常见文件夹属性和方法 (1)createNewFile(); 该方法的作用是创建指定的文件。该方法只能用于创建文件,不能用于创建文 件夹,且文件路径中包含的文件夹必须存在 File file=new ("D:\\My Document\\text.txt"); file.createNewFile(); 这样就会在D盘下的My Document 创建text.txt的记事本(注意:首先得保 证D盘下有My Documen这个文件夹) (2)mkdir(); 根据File对象的名字(路径)创建一个目录(文件夹),如果是相对目录,则新建的目

录在当前目录下 (3)mkdirs(); 如果File对象名字有多级目录,则可以调用该方法一次性创建多级目录。 (4)exists(); 判断File对象指向的文件是否存在,返回一个boolean类型(5)isDirectory(); 判断File对象指向的文件是否为目录,返回一个boolean类型的值,true或者false。 (6)getName();获得文件名称(不带路径) (7)length(); 得到File对象指向文件的长度,以字节计算,返回一个长整形的值(long);注意:在 系统中,文件夹(目录)的大小为零,也就是不占用空间,使用length()时返回的是0 (8)delete(); 删除File对象所指定的文件 (9)isFile(); 判断File对象指向的文件是不是标准文件(就像图片,音乐文件等) 三,文件的属性和方法 1.File.separator 当前操作系统的名称分隔符,等于字符串“\”.

如何使用java语言向文件中输入数据和从文件中读取数据

1、文件输入流 向文件中写入数据 Sink输出流 节点流-——文件节点 FileOutStream——字节形式存储内容 FileWriter——字符型式存储内容 import java.io.*; public class P1{ public static void main(String[]args)throws Exception{ //TODO Auto-generated method stub FileOutputStream out=new FileOutputStream("text.txt"); out.write('a'); String str="Hello world"; byte[]buffer=str.getBytes(); out.write(buffer); out.write(buffer,6,5); out.close(); } } 输出:aHello world!world 2、从文件中读取数据 Source输入流 节点流——文件节点 FileReader——字符文件 FileInputStream——字节文件 import java.io.*; public class P1{ public static void main(String[]args)throws Exception{ //TODO Auto-generated method stub FileInputStream input=new FileInputStream("text.txt"); int ch=input.read();//读入一个字节 while(ch!=-1) { System.out.print((char)ch); ch=input.read(); } input.close();

java将对象保存到文件中从文件中读取对象

1.保存对象到文件中 Java语言只能将实现了Serializable接口的类的对象保存到文件中,利用如下方法即可: public static void writeObjectToFile(Object obj) { File file =new File("test.dat"); FileOutputStream out; try { out = new FileOutputStream(file); ObjectOutputStream objOut=new ObjectOutputStream(out); objOut.writeObject(obj); objOut.flush(); objOut.close(); System.out.println("write object success!"); } catch (IOException e) { System.out.println("write object failed"); e.printStackTrace(); } } 参数obj一定要实现Serializable接口,否则会抛出 java.io.NotSerializableException异常。另外,如果写入的对象是一个容器,例如List、Map,也要保证容器中的每个元素也都是实现了Serializable 接口。例如,如果按照如下方法声明一个Hashmap,并调用writeObjectToFile方法就会抛出异常。但是如果是 Hashmap就不会出问题,因为String类已经实现了Serializable接口。另外如果是自己创建的类,如果继承的基类没有实现Serializable,那么该类需要实现Serializable,否则也无法通过这种方法写入到文件中。 Object obj=new Object(); //failed,the object in map does not implement Serializable interface HashMap objMap=new HashMap(); objMap.put("test", obj); writeObjectToFile(objMap);

java输入输出流和文件操作

Java IO流和文件操作Java流操作有关的类或接口: Java流类图结构:

1、File类 File类是对文件系统中文件以及文件夹进行封装的对象,可以通过对象的思想来操作文件和文件夹。 File类保存文件或目录的各种元数据信息,包括文件名、文件长度、最后修改时间、是否可读、获取当前文件的路径名,判断指定文件是否存在、获得当前目录中的文件列表,创建、删除文件和目录等方法。 构造方法摘要 File(File parent, String child) File(String pathname) File(String parent, String child) 构造函数 创建方法 1.boolean createNewFile() 不存在返回true 存在返回false 2.boolean mkdir() 创建目录 3.boolean mkdirs() 创建多级目录 删除方法 1.boolean delete() 2.boolean deleteOnExit() 文件使用完成后删除 例子1:列出指定文件夹的文件或文件夹 public class FileDemo1 { public static void main(String[] args){ File[] files =File.listRoots(); for(File file:files){

System.out.println(file); if(file.length()>0){ String[] filenames =file.list(); for(String filename:filenames){ System.out.println(filename); } } } } } 例子2:文件过滤 import java.io.File; public class FileTest2 { public static void main(String[] args) { File file = new File("file"); String[] names = file.list(); for(String name : names) { if(name.endsWith(".java")) { System.out.println(name); }

java读入文本文件到TextArea(打开功能实现)

java读入文本文件到TextArea(打开功能实现) Java语言: import java.awt.*; import java.io.*; import java.awt.event.*; public class IOtest extends Frame implements ActionListener{ private Frame f; private TextArea ta; //ta用于显示打开的内容 private Button btn; private FileDialog fd; private File file1 = null; //构造函数开始 public IOtest(){ btn = new Button("打开"); ta = new TextArea(5,50); btn.addActionListener(this);//给按钮添加事件监听器 } //给按钮添加行为 public void actionPerformed(ActionEvent e){ if (e.getSource()==btn) { //单击打开按钮时 fd = new FileDialog(f,"Open",FileDialog.LOAD); fd.setVisible(true); //创建并显示打开文件对话框 //if ((fd.getDirectory()!=null) && (fd.getFile()!=null)) { try { //以缓冲区方式读取文件内容 file1 = new File(fd.getDirectory(),fd.getFile()); FileReader fr = new FileReader(file1); BufferedReader br = new BufferedReader(fr); String aline; while ((aline=br.readLine()) != null)//按行读取文本 ta.append(aline+"\r\n"); fr.close(); br.close(); } catch (IOException ioe){ System.out.println(ioe); } }

java读取word文档

java读取word文档时,虽然网上介绍了很多插件poi、java2Word、jacob、itext等等,poi无法读取格式(新的API估计行好像还在处于研发阶段,不太稳定,做项目不太敢用);java2Word、jacob容易报错找不到注册,比较诡异,我曾经在不同的机器上试过,操作方法完全一致,有的机器不报错,有的报错,去他们论坛找高人解决也说不出原因,项目部署用它有点玄;itxt好像写很方便但是我查了好久资料没有见到过关于读的好办法。经过一番选择还是折中点采用rtf最好,毕竟rtf是开源格式,不需要借助任何插件,只需基本IO操作外加编码转换即可。rtf格式文件表面看来和doc没啥区别,都可以用word打开,各种格式都可以设定。 ----- 实现的功能:读取rtf模板内容(格式和文本内容),替换变化部分,形成新的rtf文档。 ----- 实现思路:模板中固定部分手动输入,变化的部分用$info$表示,只需替换$info$即可。 1、采用字节的形式读取rtf模板内容 2、将可变的内容字符串转为rtf编码 3、替换原文中的可变部分,形成新的rtf文档 主要程序如下: /** * 将制定的字符串转换为rtf编码 */ public String bin2hex(String bin) { char[] digital = "0123456789ABCDEF".toCharArray(); StringBuffer sb = new StringBuffer(""); byte[] bs = bin.getBytes(); int bit; for (int i = 0; i < bs.length;i++) { bit = (bs[i] & 0x0f0) >> 4; sb.append("\\'"); sb.append(digital[bit]); bit = bs[i] & 0x0f;

Java 对文件读写操作

Java 对文件进行读写操作的例子很多,让初学者感到十分困惑,我觉得有必要将各种方法进行 一次分析,归类,理清不同方法之间的异同点。 一.在JDK 1.0 中,通常是用InputStream & OutputStream 这两个基类来进行读写操作的。InputStream 中的FileInputStream 类似一个文件句柄,通过它来对文件进行操作,类似的,在 OutputStream 中我们有FileOutputStream 这个对象。 用FileInputStream 来读取数据的常用方法是: FileInputStream fstream = new FileInputStream(args[0]); DataInputStream in = new DataInputStream(fstream); 用in.readLine() 来得到数据,然后用in.close() 关闭输入流。 完整代码见Example 1。 用FileOutputStream 来写入数据的常用方法是: FileOutputStream out out = new FileOutputStream("myfile.txt"); PrintStream p = new PrintStream( out ); 用p.println() 来写入数据,然后用p.close() 关闭输入。 完整代码见Example 2。 二.在JDK 1.1中,支持两个新的对象Reader & Writer,它们只能用来对文本文件进行操作,而 JDK1.1中的InputStream & OutputStream 可以对文本文件或二进制文件进行操作。 用FileReader 来读取文件的常用方法是: FileReader fr = new FileReader("mydata.txt"); BufferedReader br = new BufferedReader(fr); 用br.readLing() 来读出数据,然后用br.close() 关闭缓存,用fr.close() 关闭文件。 完整代码见Example 3。 用FileWriter 来写入文件的常用方法是: FileWriter fw = new FileWriter("mydata.txt"); PrintWriter out = new PrintWriter(fw); 在用out.print 或out.println 来往文件中写入数据,out.print 和out.println的唯一区别是后者写 入数据或会自动开一新行。写完后要记得用out.close() 关闭输出,用fw.close() 关闭文件。完整代码见Example 4。 -------------------------------------------------------------- following is the source code of examples------------------------------------------------------ Example 1:

java中多种方式读文件,追加文件内容,对文件的各种操作

java中多种方式读文件,追加文件内容,对文件的各种操作 一、多种方式读文件内容。 1、按字节读取文件内容 2、按字符读取文件内容 3、按行读取文件内容 4、随机读取文件内容 2008-5-7 09:48 我思念的城市 import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.io.Reader; public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。 * @param fileName 文件的名 */ 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);

相关文档
最新文档