读文件:
1、通过File获取文件
2、打开输入流,读取文件
写文件:
1、创建文件
2、打开输出流,写入文件内容
示例:
读文件:String content = "" //文件内容字符串
//通过路径/sdcard/foo.txt打开文件
File 毕胡孙file = new File("/sdcard/foo.txt")
try {
InputStream instream = new FileInputStream(file)//读取手链输入流
InputStreamReader inputreader = new InputStreamReader(instream)//设置流读取方式
BufferedReader buffreader = new BufferedReader(inputreader)
while (( line = buffreader.readLine()) != null) {
content += line + "\n"//读取的做腔文件内容
}
}catch(Exception ex){
} 写文件:
File file = new File("/sdcard/foo.txt")//
if(!file.exists())
file.createNewFile()//如果文件不存在,创建foo.txt
try {
OutputStream outstream = new FileOutputStream(file)//设置输出流
OutputStreamWriter out = new OutputStreamWriter(outstream)//设置内容输出方式
out.write("文字内容")//输出内容到文件中
out.close()
} catch (java.io.IOException e) {
e.printStackTrace()
}
在网上查了很多关手判于修改文件的方法,不得其要领。自己想了两个取巧的办法,来解决对文件的修改。一:读取一个文件file1(FileReader and BufferedReader),进行 *** 作后写入file2(FileWriter and BufferedWriter),然后删除file1,更改file2文件名为file1(Rename()方法)。二:创建字符缓冲流(StringBuffer),读取文件内容赋给字符缓冲流,再将字符缓冲流中的内容写入到读取的文件中。例如: test.txt 这里是放在d盘的根目录下,内卜吵容如下 able adj 有才干的,能干的 active adj 主动的,活跃的 adaptable adj 适应性强的 adroit adj 灵巧的,机敏的 运行结果生成在同目录的 test1.txt中 able #adj*有才干的,能干的 active #adj*主动的,活跃的 adaptable #adj*适应性强的 adroit #adj*灵巧的,机敏的 代码: 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){ String[] sp = lineContent.split(" ")sp[0] = sp[0].concat(" *")sp[1] = sp[1].concat("# ")for(int i=0i sb.append(sp[i])}sb.append("\r\n")}FileWriter fw = new FileWriter("D:\\test2.txt")fw.write(sb.toString())br.close()fw.close()}}欢迎分享,转载请注明来源:内存溢出
评论列表(0条)