javatxt寫入
A. java往TXT文件寫入文字的問題
代碼如下:
File file4 = new File("FileTextCopy2.java");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("請輸入內容:\n");
try {
String happyString ;
BufferedWriter writer = new BufferedWriter(FileWriter(file4));
while(!(happyString=in.readLine()).equalsIgnoreCase("exit")){
System.out.println("您輸入的內容是:\""+happyString+"\",正在存儲中");
writer.write(happyString+"\n");
writer.flush();
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
寫入文件的時候最好也用帶緩沖的方法,對提升程序效率有幫助。
如果希望馬上看到寫入的效果,就執行一下flush,強制將內容立即寫入文件
」修改建議
回答含有復制內容
咦?您的答案和別的答案長的太像了,簡直就是雙胞胎,其實….分享自己的原創知識才是件最有性格的事,快去修改自己的回答吧。「
。。。原來的答案是對的,新的代碼只是改進了緩沖寫入和調用flush的位置
B. 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();
}
}
}
C. 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);
}
}
D. java 怎麼將數據寫入TXT文件
定義一個輸出文件,然後輸出就可以了,具體見下面的代碼
importjava.io.*;
publicclassStreamDemo
{
publicstaticvoidmain(Stringargs[])
{
Filef=newFile("c:\temp.txt");
OutputStreamout=null;
try
{
out=newFileOutputStream(f);
}
catch(FileNotFoundExceptione)
{
e.printStackTrace();
}
//將字元串轉成位元組數組
byteb[]="HelloWorld!!!".getBytes();
try
{
//將byte數組寫入到文件之中
out.write(b);
}
catch(IOExceptione1)
{
e1.printStackTrace();
}
try
{
out.close();
}
catch(IOExceptione2)
{
e2.printStackTrace();
}//以下為讀文件操作
InputStreamin=null;
try
{
in=newFileInputStream(f);
}
catch(FileNotFoundExceptione3)
{
e3.printStackTrace();
}
//開辟一個空間用於接收文件讀進來的數據
byteb1[]=newbyte[1024];
inti=0;
try
{
//將b1的引用傳遞到read()方法之中,同時此方法返回讀入數據的個數
i=in.read(b1);
}
catch(IOExceptione4)
{
e4.printStackTrace();
}
try
{
in.close();
}
catch(IOExceptione5)
{
e5.printStackTrace();
}
//將byte數組轉換為字元串輸出
System.out.println(newString(b1,0,i));
}
}
E. java代碼 如何向TXT文件寫入內容
向txt文件寫入內容基本思路就是獲得一個file對象,新建一個txt文件,打開I/O操作流,使用寫入方法進行讀寫內容,示例如下:
packagecommon;
importjava.io.*;
importjava.util.ArrayList;
publicclassIOTest{
publicstaticvoidmain(Stringargs[]){
ReadDate();
WriteDate();
}
/**
*讀取數據
*/
publicstaticvoidReadDate(){
Stringurl=「e:/2.txt」;
try{
FileReaderread=newFileReader(newFile(url));
StringBuffersb=newStringBuffer();
charch[]=newchar[1024];
intd=read.read(ch);
while(d!=-1){
Stringstr=newString(ch,0,d);
sb.append(str);
d=read.read(ch);
}
System.out.print(sb.toString());
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*寫入數據
*/
publicstaticvoidWriteDate(){
try{
Filefile=newFile(「D:/abc.txt」);
if(file.exists()){
file.delete();
}
file.createNewFile();
BufferedWriteroutput=newBufferedWriter(newFileWriter(file));
ArrayListResolveList=newArrayList();
for(inti=0;i<10;i++){
ResolveList.add(Math.random()*100);
}
for(inti=0;i
output.write(String.valueOf(ResolveList.get(i))+「 」);
}
output.close();
}catch(Exceptionex){
System.out.println(ex);
}
}
}
原文出自【比特網】,轉載請保留原文鏈接:http://soft.chinabyte.com/database/303/12439303.shtml
F. java 如何向txt文件中的某一行繼續寫入
Java的RandomAccessFile提供對文件的讀寫功能,與普通的輸入輸出流不一樣的是RamdomAccessFile可以任意的訪問文件的任何地方。這就是「Random」的意義所在。
相關API:
RandomAccessFile(String
name, String
mode)構造器,模式分為r(只讀),rw(讀寫)等
RandomAccessFile.readLine()方法實現對一整行的讀取,並重新定位操作位置
RandomAccessFile.write(byte[] b)用於位元組內容的寫入
示例如下:
RandomAccessFileraf=newRandomAccessFile("f:/1.txt","rw");
inttargetLineNum=10;
intcurrentLineNum=0;
while(raf.readLine()!=null){
if(currentLineNum==targetLineNum){//定位到目標行時結束
break;
}
currentLineNum++;
}
raf.write(" insert".getBytes());
raf.close();
G. java怎樣向一個文件(如txt文件)中寫入一段數據,保存後下一次打開繼續使用
這個JDK的類庫都幫我們實現好了。如FileWriter類:
public FileWriter(File file,boolean append)
throws IOException根據給定的 File 對象構造一個 FileWriter 對象。如果第二個參數為 true,則將位元組寫入文件末尾處,而不是寫入文件開始處。
例子程序如下:
import java.io.File ;
import java.io.Writer ;
import java.io.FileWriter ;
public class WriterDemo02{
public static void main(String args[]) throws Exception}
H. java如何寫入txt文件
import java.io.*;
import java.util.*;
public class LogTest{
public static void main(String[] args)
{
File log=new File("user\\log\\login.log");
String newLog="UserName:Jim Green | Date:"+new Date()+" | IP:202.65.21.14";
appendLog(log,newLog);
}
public static void appendLog(File log,String newLog)
{
Scanner sc=null;
PrintWriter pw=null;
try{
if(!log.exists())//如果文件不存在,則新建.
{
File parentDir=new File(log.getParent());
if(!parentDir.exists())//如果所在目錄不存在,則新建.
parentDir.mkdirs();
log.createNewFile();
}
sc=new Scanner(log);
StringBuilder sb=new StringBuilder();
while(sc.hasNextLine())//先讀出舊文件內容,並暫存sb中;
{
sb.append(sc.nextLine());
sb.append("\r\n");//換行符作為間隔,掃描器讀不出來,因此要自己添加.
}
sc.close();
pw=new PrintWriter(new FileWriter(log),true);
/*A.*/pw.println(sb.toString());//,寫入舊文件內容.
/*B.*/pw.println(newLog);//寫入新日誌.
/*
* 如果先寫入A,最近日誌在文件最後.
* 如是先寫入B,最近日誌在文件最前.
*/
pw.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
I. java 怎樣將txt的數據寫入到數據表中
定義一個輸出文件,然後輸出就可以了,具體見下面的代碼
import java.io.*;
public class StreamDemo
{
public static void main(String args[])
{
File f = new File("c:\\temp.txt") ;
OutputStream out = null ;
try
{
out = new FileOutputStream(f) ;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
// 將字元串轉成位元組數組
byte b[] = "Hello World!!!".getBytes() ;
try
{
// 將byte數組寫入到文件之中
out.write(b) ;
}
catch (IOException e1)
{
e1.printStackTrace();
}
try
{
out.close() ;
}
catch (IOException e2)
{
e2.printStackTrace();
}
// 以下為讀文件操作
InputStream in = null ;
try
{
in = new FileInputStream(f) ;
}
catch (FileNotFoundException e3)
{
e3.printStackTrace();
}
// 開辟一個空間用於接收文件讀進來的數據
byte b1[] = new byte[1024] ;
int i = 0 ;
try
{
// 將b1的引用傳遞到read()方法之中,同時此方法返回讀入數據的個數
i = in.read(b1) ;
}
catch (IOException e4)
{
e4.printStackTrace();
}
try
{
in.close() ;
}
catch (IOException e5)
{
e5.printStackTrace();
}
//將byte數組轉換為字元串輸出
System.out.println(new String(b1,0,i)) ;
}
}
J. java如何追加寫入txt文件
java追加寫入txt文件代碼及注釋參考如下:
publicvoidm(){
FileWriterff=null;
try{
//查看C盤是否有a.txt文件來判定是否創建
Filef=newFile("c:\a.txt");
ff=newFileWriter(f,true);//將位元組寫入文件末尾處,相當於追加信息。
}catch(IOExceptione){
e.printStackTrace();
}
PrintWriterp=newPrintWriter(ff);
p.println("這里就可以寫入要追加的內容了");//此處為追加內容
p.flush();
ff.try{
f.flush();
p.close();
ff.close();
}catch(IOExceptione){
e.printStackTrace();
}
}