java文件讀取與寫入
1. java 圖片文件的讀取和寫入問題
while(i != -1){
os.write(b, 0, b.length);
i=is.read(b, 0, b.length);
}
關鍵是這里,b僅僅是作為一個緩沖區,是可以反復使用的。
建議不要設置的太小至少1024是比較好的。
2. 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();
}
}
}
3. 跪求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,多多練習
4. 如何用Java實現對xml文件的讀取和寫入以及保存
直接附源碼import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;import org.dom4j.*;
import org.dom4j.io.XMLWriter;
public class Dom4jSample { public static void main(String[] args) {
Dom4jSample dom4jSample = new Dom4jSample();
Document document = dom4jSample.createDocument();
try{
dom4jSample.FileWrite(document);
Document documentStr = dom4jSample.StringToXML("<China>I Love!</China>");
dom4jSample.XMLWrite(documentStr);
Element legend = dom4jSample.FindElement(document);
System.out.println(legend.getText());
}
catch(Exception e)
{
}
}
/*
* Create a XML Document
*/
public Document createDocument()
{
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
Element author1 = root.addElement("Lynch");
author1.addAttribute("Age","25");
author1.addAttribute("Country","China");
author1.addText("I am great!");
Element author2 = root.addElement("Legend");
author2.addAttribute("Age","25");
author2.addAttribute("Country","China");
author2.addText("I am great!too!");
return document;
}
/*
* Create a XML document through String
*/
public Document StringToXML(String str) throws DocumentException
{
Document document = DocumentHelper.parseText(str);
return document;
}
public Element FindElement(Document document)
{
Element root = document.getRootElement();
Element legend = null;
for(Iterator i=root.elementIterator("legend");i.hasNext();)
{
legend = (Element)i.next();
}
return legend;
}
/*
* Write a XML file
*/
public void FileWrite(Document document) throws IOException
{
FileWriter out = new FileWriter("C:/Dom2jSample.xml");
document.write(out);
out.close();
}
/*
* Write a XML format file
*/
public void XMLWrite(Document document) throws IOException
{
XMLWriter writer = new XMLWriter(new FileWriter("C:/Dom2jSampleStr.xml"));
writer.write(document);
writer.close();
}
}
5. java讀取、修改、寫入txt文件
模擬:先創建一個TXT文件(內容來自控制台);然後讀取文件並在控制台輸出;最後實現對新創建的TXT文件(的數據進行排序後)的復制。分別對應三個函數,調用順序需要注意:創建、讀取、復制。
效果圖如下:綠色部分為控制台輸入的內容(當輸入end時,結束)
packagecom.;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.FileReader;
importjava.io.IOException;
importjava.io.OutputStreamWriter;
importjava.util.Arrays;
importjava.util.Scanner;
importjava.util.Vector;
publicclassCreateAndReadTxt{
//文件名稱
publicstaticStringfileName=".txt";
publicstaticStringnewFileName=".txt";
//文件路徑
publicfinalstaticStringURL=System.getProperty("user.dir");
//CreateAndReadTxt.class.getResource("/").getPath();
//創建TXT文件
publicstaticvoidcreateTxtFile(StringfName,StringfileContent){
//創建文件
fileName=fName+fileName;
Filefile=newFile(fileName);
//可以更改
file.setWritable(true);
//判斷當前路徑下是否存在同名文件
booleanisExist=file.exists();
if(isExist){
//文件存在,刪除
file.delete();
}
//寫入文件
try{
//文件寫入對象
FileOutputStreamfos=newFileOutputStream(file);
//輸入流寫入----默認字元為GBK
OutputStreamWriterosw=newOutputStreamWriter(fos);
//寫入
osw.write(fileContent);
//寫入完畢後關閉
osw.close();
System.out.println("成功創建文件: "+fileName);
}catch(IOExceptione){
System.out.println("寫入文件失敗: "+e.getMessage());
}
}
//閱讀文件
publicstaticvoidreadFile(StringfileName){
System.out.println("開始讀取文件: "+fileName);
//產生文件對象
Filefile=newFile(fileName);
//
try{
//字元讀取
FileReaderfr=newFileReader(file);
//緩沖處理
BufferedReaderbr=newBufferedReader(fr);
Stringstr="";
while((str=br.readLine())!=null){
System.out.println(str);
}
//關閉
br.close();
fr.close();
}catch(FileNotFoundExceptione){
System.out.println("讀取文件失敗: "+e.getMessage());
}catch(IOExceptione){
System.out.println("讀取文件失敗: "+e.getMessage());
}
}
//文件復制
publicstaticvoidFile(StringfromFileName,StringtoFileName){
//讀取文件
Filefile=newFile(fromFileName);
try{
FileReaderfr=newFileReader(file);
BufferedReaderbr=newBufferedReader(fr);
//定義接收變數
Vector<Double>vec=newVector<Double>();
Strings="";
while(null!=(s=br.readLine())){
vec.add(Double.parseDouble(s));
}
br.close();
fr.close();
//保存到數組並進行排序
Doubledou[]=newDouble[vec.size()];
vec.toArray(dou);
Arrays.sort(dou);
System.out.println("========復制文件=========");
//寫入新文件
newFileName="副本"+newFileName;
FilenewFile=newFile(toFileName);
FileOutputStreamfos=newFileOutputStream(newFile,true);
OutputStreamWriterosm=newOutputStreamWriter(fos);
for(Doubled:dou){
osm.write(d.doubleValue()+"
");
}
osm.close();
fos.close();
}catch(FileNotFoundExceptione){
System.out.println("讀取文件失敗: "+e.getMessage());
}catch(IOExceptione){
System.out.println("讀取文件失敗: "+e.getMessage());
}
}
publicstaticvoidmain(String[]args){
/**
*構造數據
*/
Scannerscan=newScanner(System.in);
StringBuildersb=newStringBuilder();
Strings="";
while(!("end".equals(s=scan.next()))){//當輸入end時,結束
sb.append(s);
sb.append("
");
}
scan.close();
/**
*使用數據
*/
CreateAndReadTxt.createTxtFile("creat",sb.toString());
CreateAndReadTxt.readFile(fileName);
System.out.println(fileName);
CreateAndReadTxt.File(fileName,newFileName);
CreateAndReadTxt.readFile(newFileName);
}
}
6. java怎麼讀取和寫入位元組文件開發環境 MyEclipse 8.6
InputStream
三個基本的讀方法
abstract
int
read()
:
讀取一個位元組數據,並返回讀到的數據,如果返回-1,表示讀到了輸入流的末尾。
int
read(byte[]
b)
:
將數據讀入一個位元組數組,同時返回實際讀取的位元組數。如果返回-1,表示讀到了輸入流的末尾。
int
read(byte[]
b,
int
off,
int
len)
:將數據讀入一個位元組數組,同時返回實際讀取的位元組數。如果返回-1,表示讀到了輸入流的末尾。off指定在數組b中存放數據的起始偏移位置;len指定讀取的最大位元組數。
OutputStream
三個基本的寫方法
abstract
void
write(int
b)
:往輸出流中寫入一個位元組。
void
write(byte[]
b)
:往輸出流中寫入數組b中的所有位元組。
void
write(byte[]
b,
int
off,
int
len)
:往輸出流中寫入數組b中從偏移量off開始的len個位元組的數據。
其它方法
void
flush()
:刷新輸出流,強制緩沖區中的輸出位元組被寫出。
void
close()
:關閉輸出流,釋放和這個流相關的系統資源。
7. java里往文件里讀,和讀入,意思一樣么讀,讀入,寫,寫入的區別是什麼
讀是一個位元組個讀取,讀入則可以設置一塌御個緩沖一下讀團絕岩到多個宏擾比如一下讀取1024個位元組,,這樣可以在大文件操作加快速度
寫,寫入之讀,讀入相同
8. 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(); }}
9. java如何從資料庫讀取數據並寫入txt文件
寫Java程序時經常碰到要讀如txt或寫入txt文件的情況,但是由於要定義好多變數,經常記不住,每次都要查,特此整理一下,簡單易用,方便好懂!
[java]viewplain
packagee.thu.keyword.test;
importjava.io.File;
importjava.io.InputStreamReader;
importjava.io.BufferedReader;
importjava.io.BufferedWriter;
importjava.io.FileInputStream;
importjava.io.FileWriter;
publicclasscin_txt{
staticvoidmain(Stringargs[]){
try{//防止文件建立或讀取失敗,用catch捕捉錯誤並列印,也可以throw
/*讀入TXT文件*/
Stringpathname="D:\twitter\13_9_6\dataset\en\input.txt";//絕對路徑或相對路徑都可以,這里是絕對路徑,寫入文件時演示相對路徑
Filefilename=newFile(pathname);//要讀取以上路徑的input。txt文件
InputStreamReaderreader=newInputStreamReader(
newFileInputStream(filename));//建立一個輸入流對象reader
BufferedReaderbr=newBufferedReader(reader);//建立一個對象,它把文件內容轉成計算機能讀懂的語言
Stringline="";
line=br.readLine();
while(line!=null){
line=br.readLine();//一次讀入一行數據
}
/*寫入Txt文件*/
Filewritename=newFile(".\result\en\output.txt");//相對路徑,如果沒有則要建立一個新的output。txt文件
writename.createNewFile();//創建新文件
BufferedWriterout=newBufferedWriter(newFileWriter(writename));
out.write("我會寫入文件啦 ");// 即為換行
out.flush();//把緩存區內容壓入文件
out.close();//最後記得關閉文件
}catch(Exceptione){
e.printStackTrace();
}
}
}
10. 怎麼用java從文件中讀取圖片和寫入圖片到文件里
首先導入各種需要的包:
import java.awt.Image;
import javax.imageio.ImageIO;
import java.io.*;
讀取圖片的方法如下:
Image[] array = new Image[10];
Image image = ImageIO.read(new File("d:\\source.gif"));/芹手/根據你實際情況改文件路徑吧
array[0] = image;
圖片讀出來了。
如果你有一個嫌納嫌Image對象,想把它寫入文件可以這樣做:
BufferedImage image = ImageIO.read(new File("d:\\source.gif"));
//要想保存這個對象的話你要把image聲明為BufferedImage 類型茄渣
ImageIO.write(image, "png", new File("f:\\test.png"));