java文件的读写
『壹』 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中写入文件和从文件中读取数据的最佳的代码!
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) {
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文件读写
从你函数的签名来看,推测你做的是文件复制操作。
这样复制文件,在缓存分配和计算方面,都存在风险,你可能没有正确计算这些值或者strbuffer
超出范围。可以在读写源文件的同时写入到新文件,例如:
(Filesource,Filedest)
throwsIOException{
InputStreaminput=null;
OutputStreamoutput=null;
try{
input=newFileInputStream(source);
output=newFileOutputStream(dest);
byte[]buf=newbyte[1024];
intbytesRead;
while((bytesRead=input.read(buf))>0){
output.write(buf,0,bytesRead);
}
}finally{
input.close();
output.close();
}
}
另外还有3种复制文件方法,可以参见:
4 Ways to Copy File in Java
http://examples.javacodegeeks.com/core-java/io/file/4-ways-to--file-in-java/
『肆』 java文件指针读写
用RandomAccessFile类
例如 RandomAccessFile ran=new RandomAccessFile ("*******");
将指针定义到末尾并获取ran.seek(ran.length()); long end=ran.getFilePointer();
获取倒数第二行指针位置
int j=1;
long a=0;
while((end>=0)&&(j<=2))
{
end--;
ran.seek(end);
n=ran.readByte();
if(n=='\n')
{
a=ran.getFilePointer();
j++;
}
}
a就指向了倒数第二行
接着写内容版用这个权类 我还没试过
不过用其他输入流 声明对象时 参数是true就可以了
这个你可以找找API帮助
『伍』 java中对文件进行读写操作的基本类是什么
Java.io包中包括许多类提供许多有关文件的各个方面操作。
1 输入输出抽象基类InputStream/OutputStream ,实现文件内容操作的基本功能函数read()、 write()、close()、skip()等;一般都是创建出其派生类对象(完成指定的特殊功能)来实现文件读写。在文件读写的编程过程中主要应该注意异常处理的技术。
2 FileInputStream/FileOutputStream:
用于本地文件读写(二进制格式读写并且是顺序读写,读和写要分别创建出不同的文件流对象);
本地文件读写编程的基本过程为:
① 生成文件流对象(对文件读操作时应该为FileInputStream类,而文件写应该为FileOutputStream类);
② 调用FileInputStream或FileOutputStream类中的功能函数如read()、write(int b)等)读写文件内容;
③ 关闭文件(close())。
3 PipedInputStream/PipedOutputStream:
用于管道输入输出(将一个程序或一个线程的输出结果直接连接到另一个程序或一个线程的输入端口,实现两者数据直接传送。操作时需要连结);
4管道的连接:
方法之一是通过构造函数直接将某一个程序的输出作为另一个程序的输入,在定义对象时指明目标管道对象
PipedInputStream pInput=new PipedInputStream();
PipedOutputStream pOutput= new PipedOutputStream(pInput);
方法之二是利用双方类中的任一个成员函数 connect()相连接
PipedInputStream pInput=new PipedInputStream();
PipedOutputStream pOutput= new PipedOutputStream();
pinput.connect(pOutput);
5 管道的输入与输出:
输出管道对象调用write()成员函数输出数据(即向管道的输入端发送数据);而输入管道对象调用read()成员函数可以读起数据(即从输出管道中获得数据)。这主要是借助系统所提供的缓冲机制来实现的。
6随机文件读写:
RandomAccessFile类(它直接继承于Object类而非InputStream/OutputStream类),从而可以实现读写文件中任何位置中的数据(只需要改变文件的读写位置的指针)。
随机文件读写编程的基本过程为:
① 生成流对象并且指明读写类型;
② 移动读写位置;
③ 读写文件内容;
④ 关闭文件。
七里河团队答疑助人,希望我的回答对你有所帮助
『陆』 Java文件读写
实用的模糊(通配符)文件查找程序
1 import java.io.File;
2 import java.util.regex.Matcher;
3 import java.util.regex.Pattern;
4 import java.util.ArrayList;
5
6 /** *//**
7 * <p>Title: FileService </p>
8* <p>Description: 获取文件 </p>
9* <p>Copyright: Copyright (c) 2007</p>
10* <p>Company: </p>
11* @author not attributable
12* @version 1.0
13*/
14public class FileService {
15 public FileService() {
16 }
17
18 /** *//**
19 * 在本文件夹下查找
20 * @param s String 文件名
21 * @return File[] 找到的文件
22 */
23 public static File[] getFiles(String s)
24 {
25 return getFiles("./",s);
26 }
27
28 /** *//**
29 * 获取文件
30 * 可以根据正则表达式查找
31 * @param dir String 文件夹名称
32 * @param s String 查找文件名,可带*.?进行模糊查询
33 * @return File[] 找到的文件
34 */
35 public static File[] getFiles(String dir,String s) {
36 //开始的文件夹
37 File file = new File(dir);
38
39 s = s.replace('.', '#');
40 s = s.replaceAll("#", "\\\\.");
41 s = s.replace('*', '#');
42 s = s.replaceAll("#", ".*");
43 s = s.replace('?', '#');
44 s = s.replaceAll("#", ".?");
45 s = "^" + s + "$";
46
47 System.out.println(s);
48 Pattern p = Pattern.compile(s);
49 ArrayList list = filePattern(file, p);
50
51 File[] rtn = new File[list.size()];
52 list.toArray(rtn);
53 return rtn;
54 }
55
56 /** *//**
57 * @param file File 起始文件夹
58 * @param p Pattern 匹配类型
59 * @return ArrayList 其文件夹下的文件夹
60 */
61
62 private static ArrayList filePattern(File file, Pattern p) {
63 if (file == null) {
64 return null;
65 }
66 else if (file.isFile()) {
67 Matcher fMatcher = p.matcher(file.getName());
68 if (fMatcher.matches()) {
69 ArrayList list = new ArrayList();
70 list.add(file);
71 return list;
72 }
73 }
74 else if (file.isDirectory()) {
75 File[] files = file.listFiles();
76 if (files != null && files.length > 0) {
77 ArrayList list = new ArrayList();
78 for (int i = 0; i < files.length; i++) {
79 ArrayList rlist = filePattern(files[i], p);
80 if (rlist != null) {
81 list.addAll(rlist);
82 }
83 }
84 return list;
85 }
86 }
87 return null;
88 }
89
90 /** *//**
91 * 测试
92 * @param args String[]
93 */
94 public static void main(String[] args) {
95 }
96}
『柒』 Java读写文件的几种方法
java读取配置文件的几种方法如下:
方式一:采用ServletContext读取,读取配置文件的realpath,然后内通过文件流读取出容来。因为是用ServletContext读取文件路径,所以配置文件可以放入在web-info的classes目录中,也可以在应用层级及web-info的目录中。文件存放位置具体在eclipse工程中的表现是:可以放在src下面,也可放在web-info及webroot下面等。因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xml和properties。缺点:不能在servlet外面应用读取配置信息。
方式二:采用ResourceBundle类读取配置信息,
优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。缺点:只能加载类classes下面的资源文件且只能读取.properties文件。
『捌』 java怎样实现读写TXT文件
主要有用到java原生态的Io类,没有第三个包。直接上代码:
importjava.io.*;
publicclasswrite{
publicstaticvoidmain(String[]args){
write("E://123.txt","hello");
}
publicstaticvoidwrite(Stringpath,Stringcontent){
try{
Filef=newFile(path);
if(f.exists()){
System.out.println("文件存在");
}else{
System.out.println("文件不存在,正在创建...");
if(f.createNewFile()){
System.out.println("文件创建成功!");
}else{
System.out.println("文件创建失败!");
}
}
BufferedWriteroutput=newBufferedWriter(newFileWriter(f));
output.write(content);
output.close();
}catch(Exceptione){
e.printStackTrace();
}
}
}
『玖』 java中如何从文件中读取数据
分为读字节,读字符两种读法
◎◎◎FileInputStream 字节输入流读文件◎◎◎
public class Maintest {
public static void main(String[] args) throws IOException {
File f=new File("G:\\just for fun\\xiangwei.txt");
FileInputStream fin=new FileInputStream(f);
byte[] bs=new byte[1024];
int count=0;
while((count=fin.read(bs))>0)
{
String str=new String(bs,0,count); //反复定义新变量:每一次都 重新定义新变量,接收新读取的数据
System.out.println(str); //反复输出新变量:每一次都 输出重新定义的新变量
}
fin.close();
}
}
◎◎◎FileReader 字符输入流读文件◎◎◎
public class Maintest {
public static void main(String[] args) throws IOException {
File f=new File("H:\\just for fun\\xiangwei.txt");
FileReader fre=new FileReader(f);
BufferedReader bre=new BufferedReader(fre);
String str="";
while((str=bre.readLine())!=null) //●判断最后一行不存在,为空
{
System.out.println(str);
}
bre.close();
fre.close();
}
}
『拾』 JAVA文件读写
package javaTest;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("D:\\test.txt"));
StringBuffer sb = new StringBuffer();
String lineContent = null ;
while( (lineContent = br.readLine()) != null){
StringTokenizer st = new StringTokenizer( lineContent," " );
for( int t=0; st.hasMoreElements() ; t++){
String word = (String) st.nextElement();
sb.append( word );
if( t== 0){
sb.append(" #");
}
if( t==1){
sb.append("*");
}
}
sb.append("\n");
}
PrintWriter pw = new PrintWriter("D:\\test1.txt");
pw.write(sb.toString());
br.close();
pw.close();
}
}
test.txt 这里是放在d盘的根目录下,内容如下
able adj 有才干的,能干的
active adj 主动的,活跃的
adaptable adj 适应性强的
adroit adj 灵巧的,机敏的
运行结果生成在同目录的 test1.txt中
able #adj*有才干的,能干的
active #adj*主动的,活跃的
adaptable #adj*适应性强的
adroit #adj*灵巧的,机敏的