导航:首页 > 编程语言 > java文件写入读取

java文件写入读取

发布时间:2023-06-03 16:31:36

java中如何实现文件的批量读取并提取部分内容写入一个新文件。 单一文件读取写入参照补充

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Testa
{
public static void main(String[] args)
{
//传入参数为文件目录
test("d:/a.txt");
}

public static void test(String filePath){
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}

String []columnName = {"Id", "Name", "Languages", "Math", "English"}; //列名
int []courseIndexs = {2, 3, 4}; //课程对应的列
int i,j,index;
String line;
List> students = new ArrayList>();
//记录Id和总值,用于排序
List> sortList = new ArrayList>();
try {
br.readLine(); //去掉第一行
while((line = br.readLine()) != null){
index = 0;
String []se = line.split(" ");
Map student = new HashMap();
for(i = 0; i < se.length; i++){
if("".equals(se[i])){
continue;
}
if(index >= columnName.length){
continue;
}
student.put(columnName[index], se[i]);
index++;
}
//计算平均值,总值
double total = 0;
for(j = 0; j < courseIndexs.length; j++){
total += Double.parseDouble((String) student.get(columnName[courseIndexs[j]]));
}
double average = total / courseIndexs.length;
//只取一位小数
average = Math.round(average * 10)/10;
student.put("Total", total);
student.put("Average", average);

Map sort = new HashMap();
sort.put("Id", student.get("Id"));
sort.put("Total", student.get("Total"));
sortList.add(sort);

students.add(student);
}
br.close();

//排序
for(i = 0; i < sortList.size(); i++){
for(j = i + 1; j < sortList.size(); j++){
if((Double)sortList.get(i).get("Total") < (Double)sortList.get(j).get("Total")){
Map temp = sortList.get(i);
sortList.set(i, sortList.get(j));
sortList.set(j, temp);
}
}
}
Map sortedId = new HashMap();
for(i = 0; i < sortList.size(); i++){
sortedId.put(sortList.get(i).get("Id"), i+1);
}

//设定序号
for(j = 0; j < students.size(); j++){
students.get(j).put("Order", sortedId.get(students.get(j).get("Id")));
}

//输出(写到原文件)
//PrintWriter pw = new PrintWriter(new File(filePath));
//输出(写到其他文件)
PrintWriter pw = new PrintWriter(new File("D:/b.txt"));

pw.println("Id\tName\tLan\tMath\tEnglish\tAverage\tTotal\tSort");
int cIndex;
for(i = 0; i < students.size(); i++){
Map st = students.get(i);
cIndex = 0;
pw.println(st.get(columnName[cIndex++]) + "\t" + st.get(columnName[cIndex++])
+ "\t" + st.get(columnName[cIndex++])+ "\t" + st.get(columnName[cIndex++])
+ "\t" + st.get(columnName[cIndex++])
+ "\t" + st.get("Total")
+ "\t" + st.get("Average")
+ "\t" + st.get("Order"));
}
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Ⅱ java中如何使用缓冲区对文件进行读写操作

首先,了解下什么是缓冲区:
电脑内存分成5个区,他们分别是堆、栈、自由存储区、全局/静态存储区和常量存储区。

栈——就是那些由编译器在需要的时候分配,在不需要的时候自动清楚的变量的存储区。里面的变量通常是局部变量、函数参数等。

堆——就是那些由new分配的内存块,他们的释放编译器不去管,由我们的应用程序去控制,一般一个new就要对应一个delete.如果程序员没有释放掉,那么在程序结束后,操作系统会自动回收。

自由存储区——就是那些由malloc等分配的内存块,他和堆是十分相似的,不过它是用free来结束自己的生命的。

全局/静态存储区——全局变量和静态变量被分配到同一块内存中,在以前的C语言中,全局变量又分为初始化的和未初始化的,在C++里面没有这个区分了,他们共同占用同一块内存区。

常量存储区,这是一块比较特殊的存储区,他们里面存放的是常量,不允许修改(当然,你要通过非正当手段也可以修改)

电脑缓冲区就是预留下来的做为急用的那一部分,为暂时置放输出或输入资料的内存。

如何对缓冲区进行操作:
当我们读写文本文件的时候,采用Reader是非常方便的,比如FileReader,InputStreamReader和BufferedReader。其中最重要的类是InputStreamReader, 它是字节转换为字符的桥梁。你可以在构造器重指定编码的方式,如果不指定的话将采用底层操作系统的默认编码方式,例如GBK等。使用FileReader读取文件:
FileReader fr = new FileReader("ming.txt");
int ch = 0;
while((ch = fr.read())!=-1 )
{
System.out.print((char)ch);
}
其中read()方法返回的是读取得下个字符。当然你也可以使用read(char[] ch,int off,int length)这和处理二进制文件的时候类似。
事实上在FileReader中的方法都是从InputStreamReader中继承过来的。read()方法是比较好费时间的,如果为了提高效率我们可以使用BufferedReader对Reader进行包装,这样可以提高读取得速度,我们可以一行一行的读取文本,使用readLine()方法。
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("ming.txt")));
String data = null;
while((data = br.readLine())!=null)
{
System.out.println(data);
}
了解了FileReader操作使用FileWriter写文件就简单了,这里不赘述。
Eg.我的综合实例:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class testFile {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// file(内存)----输入流---->【程序】----输出流---->file(内存)
File file = new File("d:/temp", "addfile.txt");
try {
file.createNewFile(); // 创建文件
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// 向文件写入内容(输出流)
String str = "亲爱的小南瓜!";
byte bt[] = new byte[1024];
bt = str.getBytes();
try {
FileOutputStream in = new FileOutputStream(file);
try {
in.write(bt, 0, bt.length);
in.close();
// boolean success=true;
// System.out.println("写入文件成功");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// 读取文件内容 (输入流)
FileInputStream out = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(out);
int ch = 0;
while ((ch = isr.read()) != -1) {
System.out.print((char) ch);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}

Ⅲ 跪求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文件读写

在网上查了很多关于修改文件的方法,不得其要领。自己想了两个取巧的办法,来解决对文件的修改。一:读取一个文件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=0;i sb.append(sp[i]);}sb.append("\r\n");}FileWriter fw = new FileWriter("D:\\test2.txt"); fw.write(sb.toString()); br.close(); fw.close(); }}

阅读全文

与java文件写入读取相关的资料

热点内容
法国两男一女电影 浏览:292
有一部电影叫什么湖泊 浏览:83
大尺度电影床戏视频 浏览:672
压缩机线圈烧了可以修吗 浏览:783
cctv5加密收费吗 浏览:211
理财app关闭该怎么办 浏览:452
服务器如何配置多个https域名 浏览:86
怎样制作文件夹的中文翻译 浏览:518
泰剧大尺度影片 浏览:730
为什么python适合做算法 浏览:810
新疆政务服务app中如何实名认证 浏览:224
重生成小孩 浏览:104
二战中的加密技术 浏览:515
美逛app如何建群 浏览:819
iphone用什么app3d扫描 浏览:289
冠生园葱油压缩饼干 浏览:503
Linux库文件安装 浏览:225
解压玩具黑猩猩 浏览:967
单片机中断实验程序注释 浏览:695
安卓手机下什么软件连电脑 浏览:725