Java文件读写操作代码实现
Java文件读写操作代码实现
package test;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* 一、BufferedReader类 public class BufferedReader extends Reader
* 从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。可以指定缓冲区的大小,或者可使用默认的大小。大多数情况下,默认值足够大。
* 通常,Reader 所作的每个读取请求都会导致对底层字符或字节流进行相应的读取请求。因此,建议用 BufferedReader包装所有其 read()
* 操作可能开销很高的 Reader(如 FileReader和 InputStreamReader)。
* BufferedReader流能够读取文本行,通过向BufferedReader传递一个Reader对象
* ,来创建一个BufferedReader对象,之所以这样做是因为FileReader没有提供读取文本行的功能.
*
* 二、InputStreamReader类
*
* InputStreamReader 将字节流转换为字符流。是字节流通向字符流的桥梁。如果不指定字符集编码,该解码过程将使用平台默认的字符编码,如:GBK。
*
* 构造方法:
*
* InputStreamReader isr = new InputStreamReader(InputStream
* in);//构造一个默认编码集的InputStreamReader类
*
* InputStreamReader isr = new InputStreamReader(InputStream in,String
* charsetName);//构造一个指定编码集的InputStreamReader类。
*
* 参数 in对象通过 InputStream in = System.in;获得。//读取键盘上的数据。
*
* 或者 InputStream in = new FileInputStream(String fileName);//读取文件中的数据。可以看出
* FileInputStream 为InputStream的子类。
*
* 主要方法:int read();//读取单个字符。 int read(char []cbuf);//将读取到的字符存到
数组中。返回读取的字符数。
*
* 三、FileWriter(少量文字)和 BufferedWriter(大量文字)实现简单文件写操作
* @author hulk
*/
public class FileReadWriteUtil {
// "D:\\demo.txt"
private static String PATH = "/home/hulk/devtools/adt-bundle-linux-x86_64-20140702/workspace/JavaTest/readme.txt";// or
private static boolean debugMode = true;
/**
* @param args
*/
public static void main(String[] args) {
// readSystemInputText();//读取键盘输入文字信息
// testBufferReader();
String aaaaPath = "/home/hulk/aaaa.txt";
String aaaPath = "/home/hulk/aaa.txt";
String text = readResourceFile(aaaaPath).toString();// 读取文件资源
String appendtext =
"\n\nAAAAAAAAAAAAaaaaaaaaaaaaaaaa\nBBBBBBBBBBBBBBBBbbbbbbbbbbbbb";
writeText(aaaPath, text, false);
readResourceFile(aaaPath);// 读取文件资源
}
private static void testBufferReader() {
try {
readFileNoBuffer(PATH, 2048);// 不使用缓冲区
readFileByBuffer(PATH);// 使用缓冲区,适用于,读取完整文件} catch (IOException e) {
e.printStackTrace();
}
}
public static void setDebugMode(boolean debugMode) { FileReadWriteUtil.debugMode = debugMode;
}
/**
* 没有缓冲区,只能使用read()方法,得指定要读取的字符长度
*
* @throws IOException
*/
public static String readFileNoBuffer(String path, int readChars) throws IOException {
// 读取字节流
// InputStream in = System.in;//读取键盘的输入。
InputStream in = new FileInputStream(path);// 读取文件的数据。
// 将字节流向字符流的转换。要启用从字节到字符的有效转换,
// 可以提前从底层流读取更多的字节.
InputStreamReader isr = new InputStreamReader(in);// 读取
char[] cha = new char[readChars];
int len = isr.read(cha);
String text = new String(cha, 0, len);
log(text);
isr.close();
return text;
}
/**
* 使用缓冲区可以使用缓冲区对象的 read() 和 readLine()方法。
*
* @throws IOException
*/
public static StringBuffer readFileByBuffer(String path) throws IOException { // 读取字节流
InputStream in = new FileInputStream(path);// 读取文件上的数据。
InputStreamReader isr = new InputStreamReader(in);// 将字节流向字符流的转换BufferedReader bufr = new BufferedReader(isr);// 创建字符流缓冲区
StringBuffer buffer = new StringBuffer();
String line;
while ((line = bufr.readLine()) != null) {
buffer.append(line).append("\n");
log(line);
}
isr.close();
return buffer;
}
public static StringBuffer readText(String filePath) {
BufferedReader br = null;
StringBuffer buffer = null;
try {
br = new BufferedReader(new FileReader(filePath));
String line = null;
buffer = new StringBuffer();
while ((line = br.readLine()) != null) {
buffer.append(line).append("\n");
log(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return buffer;
}
public static StringBuffer readtextByChar(String filePath) {
StringBuffer text = null;
FileReader reader = null;
try {
reader = new FileReader(filePath);
int ch = 0;
text = new StringBuffer();
while ((ch = reader.read()) != -1) { text.append((char)ch);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return text;
}
/**
* 使用FileWriter类写文本文件, 仅限制少量文字
* Note: //使用这个构造函数时,如果存在filePath.txt文件,则先把这个文件给删除掉,然后创建新的filePath.txt
* @param filePath
* @param text
* @return the FileWriter object, null if throws Exception
*/
public static FileWriter writeText(String filePath, String text) {
return writeText(filePath, text, false);
}
/**
* 使用FileWriter类写文本文件
* @param filePath
* @param text
* @param append true: 如果存在filePath.txt文件,则直接在后面追加字符串; false: 直接删除原文件
* @return the FileWriter object, null if throws Exception
*/
public static FileWriter writeText(String filePath, String text, boolean append) {
FileWriter writer = null;
try {
writer = new FileWriter(filePath, append);
writer.write(text);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return writer;
}
/**
* 向文件写入字符串。可以时较大字符串.
* 注意\n不一定在各种计算机上都能产生换行的效果:
*
可以用返回的BufferedWriter对象执行一下函数实现换行:
* BufferedWriter out = FileReadWriteUtil.writeByBuffer("/demo.txt", "AAA", true);
* out.newLine();//实现换行
* @param filePath
* @param text
* @return The BufferedWriter object, null if throws Exception
*/
public static BufferedWriter writeBufferText(String filePath, String text, boolean append) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(filePath, append));
out.write(text);
out.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return out;
}
public static boolean makeFile(String filePath) { File file = new File(filePath);
if(!file.exists()) {
if(file.isFile()) {
File p = file.getParentFile();
if(!p.exists()) {
makeDir(p.getAbsolutePath());
}
try {
return file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return false;
}
} else {
System.out.print("Not a file path: " + filePath);
return false;
}
} else {
return true;
}
}
public static boolean makeDir(String dir) {
File p = new File(dir);
if(!p.exists()) {
return p.mkdirs();
} else {
return true;
}
}
/**
* 键盘输入读取文字信息
*/
public static String readSystemInputText() {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("请输入一系列文字,可包括空格,完成后按回车即可显示出来:");
System.out.print("请在这里输入文字:");
String text = null;
try {
text = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
log("你输入的文字为:" + text);
return text;
}
/**
* 按行读取文件信息
*
* @param path
* 文件存放路径,;如果文件在项目根目录下,直接用文件名即可eg. "readme.txt"
*/
public static StringBuffer readResourceFile(String path) { StringBuffer buffer = null;
try {
// 读取文件,并且以utf-8的形式写出去
BufferedReader bufread;
BufferedInputStream bis = getResourceInputStream(path);
if (bis == null)
return null;
String read;
bufread = new BufferedReader(new InputStreamReader((bis)));
buffer = new StringBuffer();
while ((read = bufread.readLine()) != null) {
buffer.append(read).append("\n");
log(read);
}
bufread.close();
bis.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return buffer;
}
static BufferedInputStream getResourceInputStream(String filePath) { try {
return new BufferedInputStream(new FileInputStream(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
private static void log(String text) {
if (debugMode) {
System.out.println(text);
}
}
}
调用jar包外配置文件
项目中,经常把一部分功能独立出来,做一个java project,然后打成jar包供其他项目引用。这时候,如果jar包中需要读取配置文件信息,则很少把该配置打进jar包,因为它不方便修改,更多都是采用jar包读取外部配置文件。案例: 项目工程名:auth -- 很明显,做鉴权使用的 项目配置文件:init.properties log4j.properties 项目引用jar包: lib/servlet-api.jar lib/log4j-1.2.15.jar lib/commons-collections-3.1.jar lib/commons-logging-1.0.4.jar lib/commons-pool.jar lib/ojdbc14.jar 读取配置文件示例: 目录结构如下:
解决方案I:自定义manifest.mf 文件 解释: Manifest-Version: 1.0 版本号,没啥特殊含义,但一定要有;Class-Path: 所有引用的jar包 注意: 每个“:”后面都要加空格,Class-Path中每个jar包间也加空格最后一行为空行 截图如下: b.通过Eclipse 到处jar包 右键项目工程----Export -- 选择Java下JAR File,下一步
件外部读取),选择导出jar包的位置; 注意:右侧的.classpath这些都不要选中,只把src下的java文件打包。
下一步 下一步:选中自定义的manifest.mf文件,完成 测试: 新建项目,导入刚刚生成的jar包和jar需要的所有包(把jar包所在工程lib下所有引用jar
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读取jar包内部配置文件
package com.test; import java.io.File; import java.io.IOException; import java.io.InputStream; import https://www.360docs.net/doc/996079148.html,.URL; import java.util.Properties; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class Test9 { public static void main(String[] args) throws IOException { String jarName="/test_p.jar";//Jar包所在的位置 String fileName="config/application.properties";//文件在jar包里的路径 String resource = Test9.class.getResource(jarName).getFile(); File file = new File(resource); JarFile jarFile = new JarFile(file);//读入jar文件 JarEntry entry = jarFile.getJarEntry(fileName); InputStream input = jarFile.getInputStream(entry);//读入需要的文件 Properties props = new Properties(); props.load(input); System.out.println(props.getProperty("Driver")); jarFile.close(); } }
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/996079148.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/996079148.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读取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 读取配置文件和修改配置文件(ServiceIP.properties)(原创) package espeed.util; import java.io.*; import java.util.Properties; /* * 配置短信服务器IP(配置文件建在SRC下,ServiceIP.properties) */ public class EditServiceIP { private static Properties properties=new Properties(); private static EditServiceIP esip; public EditServiceIP(){} public static EditServiceIP getInstance(){ if(esip==null) esip=new EditServiceIP(); return esip; } //取得短信服务器IP public String getSmsServiceIP(){ InputStream is=EditServiceIP.class.getClassLoader().getResourceAsSt ream("ServiceIP.properties"); try { properties.load(is); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("------------取得短信服务器IP地址发生IO异常"); } String provalue=properties.getProperty("SMS.ServiceIP"); return provalue; } //修改短信服务器IP public String modifySmsServieIP(String smsServiceIP){ File file=new File(EditServiceIP.class.getClassLoader().getResource("S erviceIP.properties").getPath()); try{ properties.load(new FileInputStream(file)); 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(); } } } 执行结果如下: 项目中一个需求就是所有的功能都是插件的形式装入系统,这就需要利用Spring去动态加载某一位置下的配置文件,就总结了下Spring中加载xml配置文件的方式, xml是最常见的spring 应用系统配置源。Spring中的几种容器都支持使用xml装配bean,包括:XmlBeanFactory, ClassPathXmlApplicationContext, FileSystemXmlApplicationContext, XmlWebApplicationContext, ..... 一: XmlBeanFactory 引用资源 1.Resource cr = new ClassPathResource("applicationContext.xml"); BeanFactory bf=new XmlBeanFactory(cr); UserDao userDao = (UserDao)bf.getBean("userDao"); 二: ClassPathXmlApplicationContext 编译路径 使用ClassPathXmlApplicationContext对象获取,必须把applicationContext.xml放置到类的加载路径中,也就是Src下面 1.ApplicationContext factory=new ClassPathXmlApplicationContext("classpath:appcontext.xml"); // src目录下的 2.ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao userDao = (UserDao)context.getBean("userDao"); 3.ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext-oracle.xml","applicationContext.xml"}); UserDao userDao = (UserDao)context.getBean("userDao"); // src/conf 目录下的 4.ApplicationContext factory=new ClassPathXmlApplicationContext("conf/appcontext.xml"); 5.ApplicationContext factory=new ClassPathXmlApplicationContext("file:G:/Test/src/appcontext.xml"); 三: FileSystemXmlApplicationContext用文件系统 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); 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); } 一. 创建文件 (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 当前操作系统的名称分隔符,等于字符串“\”. 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(); spring 框架的xml文件如何读取properties文件数据 第一步:在spring配置文件中 注意:value可以多配置几个properties文件 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 是字符流通向字节流的桥梁。 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 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读取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;读取配置文件和修改配置文件(ServiceIP.properties)(原创)
Java读取Excel文件的几种方法
Spring中加载xml配置文件的几种方式
java读写文件避免中文乱码
java文件读写代码
java File文件操作和文件流的详解(福哥出品)
如何使用java语言向文件中输入数据和从文件中读取数据
spring读取properties
Java流(文件读写操作)
java将对象保存到文件中从文件中读取对象
java输入输出流和文件操作
java读取word文档