導航:首頁 > 編程語言 > java的文件輸入輸出

java的文件輸入輸出

發布時間:2022-05-25 12:05:09

java如何從文件輸入輸出

// 讀取文件
public class ReadTextFileExample {
public static void main(String[] args ) {
File file = new File("d:\\caipiao_3.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;

try {
reader = new BufferedReader(new FileReader(file));
String text = null;

// repeat until all lines is read
while ((text = reader.readLine()) != null) {
contents.append(text).append(System.getProperty("line.separator"));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (reader != null) {
reader.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}

// show file contents here
System.out.println(contents.toString());
}
}
// 寫出文件
public class WriteTextFileExample {
public static void main(String[] args ) {
FileOutputStream fos = null;
BufferedWriter bw = null;
try {
File file = new File("abc.txt");
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("this is a sample!");
}
catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
finally {
try {
if (bw != null)
bw.close();
if (fos != null)
fos.close();
}
catch (IOException ie) {
}
}
}
}

② Java中如何實現文件的輸入輸出

程序如下:
<span style="color:#990000;">

</span>File file1 = new File("/home/a123/a");

if (file1.exists()) {
System.out.println("存在文件夾a");
} else {
file1.mkdir(); // 文件夾的創建 創建文件夾/home/a123/a
}
File file2 = new File("/home/a123/a/test");
if (file2.exists()) {
System.out.println("存在文件夾或者文件test");
} else {
try {
file2.createNewFile(); // 文件的創建,注意與文件夾創建的區別
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* 最簡單的文件讀寫方法是使用類FileWriter
* (它的父類依次是java.io.OutputStreamWriter——>java.io.Writer——>java.lang.Object );
*/

// 下面是向文件file2裡面寫數據
try {
FileWriter fileWriter = new FileWriter(file2);
String s = new String("This is a test! \n" + "aaaa");
fileWriter.write(s);
fileWriter.close(); // 關閉數據流

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

/*
* 這樣寫數據的話,是完全更新文件test裡面的內容,即把以前的東西全部刪除,重新輸入。
* 如果不想刪除以前的數據,而是把新增加的內容增添在文件末尾處。只需要在創建FileWriter對象時候,使用另外一個構造函數即可:
* FileWriter fileWriter=new FileWriter(file2,true);
*/

// 下面是從文件file2讀東西
try {
FileReader fileReader = new FileReader(file2);
String s = null;
char ch;
try {
char[] c = new char[100];
fileReader.read(c,0,2); // 具體想得到文件裡面的什麼值(單個char?int?還是String?),
System.out.println(c);
fileReader.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**
* 具體想得到文件裡面的什麼值(單個char?int?還是String?),需要知道不通read的不同用法:
* 1. int read() 讀取單個字元。
* 2. int read(char[] cbuf) 將字元讀入數組。 可以再將字元型數組轉化位字元串
* 3. int read(char[] cbuf,int off,int len) 將字元讀入數組的某一部分。
* 這三個方法都返回一個int值,作用是:讀取的字元數,如果已到達流的末尾,則返回 -1.
*/

}

③ java的輸入輸出中,如果數據相對於外部文件是出去了,我們稱之為輸出操作對嗎

不是的,輸入/輸出是相對於程序說的。把數據傳遞給程序的變數,就是輸入;把程序變數的值,發出去(給顯示器或者文件),就是輸出。

④ java實現文件的輸入輸出的主要使用的類是什麼

ava的輸入輸出功能來自java.io 包中的InputStream類、OutputStream類、Reader類和Writer類以及繼承它們的各種子類。

⑤ java輸入文件名,輸出該文件的內容

java讀取文件的內容,使用BufferedReader來讀取,通過Scanner對象獲取輸入的文件名,來讀取這個文件的內容並輸出,具體示例代碼如下:

publicclasstxttest{
/**
*讀取txt文件的內容
*@paramfile想要讀取的文件對象
*@return返迴文件內容
*/
publicstaticStringtxt2String(Filefile){
Stringresult="";
try{
BufferedReaderbr=newBufferedReader(newFileReader(file));//構造一個BufferedReader類來讀取文件
Strings=null;
while((s=br.readLine())!=null){//使用readLine方法,一次讀一行
result=result+" "+s;
}
br.close();
}catch(Exceptione){
e.printStackTrace();
}
returnresult;
}

publicstaticvoidmain(String[]args){
Scannerscan=newScanner(System.in);
System.out.println("請輸入文件名:");
Stringstr=scan.next();
Stringmulu="C:\Users\hp\Desktop\"+str+".txt";//文件具體目錄
Filefile=newFile(mulu);
System.out.println(txt2String(file));
}
}

⑥ java中讀入和輸出文本文件

/**
*測試3:從文本文件中讀取數據
*/
staticvoidtestExample03(){
//1、在內存中打開要讀取文件的字元流對象
try{
Readerreader=newFileReader("e:/ReadMe.log");
//2、從字元流中讀取數據
//一次讀取一個字元(麻煩)
/*intnum=reader.read();
System.out.println((char)num);
num=reader.read();
System.out.println((char)num);*/
//一次讀取一個數組(必須確定數組的長度)
/*char[]cbuf=newchar[10];
reader.read(cbuf);
System.out.println(newString(cbuf));*/
//循環讀取,一次就讀一個
intch=reader.read();
StringBufferbuffer=newStringBuffer();
while(ch!=-1){//讀取成功
buffer.append((char)ch);
ch=reader.read();
}
System.out.println(buffer.toString());
//3、關閉流
reader.close();
}catch(FileNotFoundExceptione){
System.out.println("要讀取的文件不存在:"+e.getMessage());
}catch(IOExceptione){
System.out.println("文件讀取錯誤:"+e.getMessage());
}
}
/**
*測試4:向文本文件中寫入數據
*/
staticvoidtestExample04(){
System.out.println("請輸入內容:");
Stringtext=input.next();
try{
//1、打開流
Writerw=newFileWriter("e:/測試.txt",true);
//2、寫入內容
w.write(text);
//3、關閉流
w.close();
}catch(IOExceptione){
System.out.println("文件寫入錯誤:"+e.getMessage());
}
}
/**
*測試5:使用效率高的字元流讀寫數據
*/
staticvoidtestExample05(){
try{
//1、創建流對象
Readerreader=newFileReader("e:/ReadMe.log");
//構建高效流對象
BufferedReaderbuffReader=newBufferedReader(reader);

//2、讀取一行字元串
Stringline=buffReader.readLine();
StringBufferbuffer=newStringBuffer();
while(line!=null){
buffer.append(line+" ");
line=buffReader.readLine();
}
System.out.println(buffer.toString());;
//3、關閉流
buffReader.close();
reader.close();

Writerw=newFileWriter("e:/NewReadMe.txt");
BufferedWriterbuffWriter=newBufferedWriter(w);

buffWriter.write(buffer.toString());

buffWriter.close();
w.close();
System.out.println("寫入成功!");

}catch(FileNotFoundExceptione){
System.out.println("要讀取的文件不存在:"+e.getMessage());
}catch(IOExceptione){
System.out.println("文件讀取錯誤:"+e.getMessage());
}
}

⑦ java怎麼輸出

java控制台輸出由print( ) 和 println( )來完成最為簡單。這兩種方法由rintStream(System.out引用的對象類型)定義。盡管System.out是一個位元組流,用它作為簡單程序的輸出是可行的。因為PrintStream是從OutputStream派生的輸出流,它同樣實現低級方法write(),write()可用來向控制台寫數據。PrintStream 定義的write( )的最簡單的形式如下:

void write(int byteval)

該方法按照byteval指定的數目向文件寫位元組。盡管byteval 定義成整數,但只有低位的8個位元組被寫入。下面的短例用 write()向屏幕輸出字元「A」,然後是新的行。

// Demonstrate System.out.write().

class WriteDemo {

public static void main(String args[]) {

int b;

b = 'A';

System.out.write(b);

System.out.write(' ');

}

}

一般不常用write()來完成向控制台的輸出(盡管這樣做在某些場合非常有用),因為print()和println() 更容易用。

四、PrintWriter類

盡管Java允許用System.out向控制台寫數據,但建議僅用在調試程序時或在常式中。對於實際的程序,Java推薦的向控制台寫數據的方法是用PrintWriter流。PrintWriter是基於字元的類。用基於字元類向控制台寫數據使程序更為國際化。PrintWriter定義了多個構造函數,這里所用到的一個如下:

PrintWriter(OutputStream outputStream, boolean flushOnNewline)

outputStream是OutputStream類的對象,flushOnNewline控制Java是否在println()方法被調用時刷新輸出流。如果flushOnNewline為true,刷新自動發生,若為false,則不發生。

PrintWriter支持所有類型(包括Object)的print( )和println( )方法,這樣,就可以像用ystem.out那樣用這些方法。如果遇到不同類型的情況,PrintWriter方法調用對象的toString()方法並列印結果。用PrintWriter向外設寫數據,指定輸出流為System.out並在每一新行後刷新流。例如這行代碼創建了與控制台輸出相連的PrintWriter類。

PrintWriter pw = new PrintWriter(System.out, true);

下面的應用程序說明了用PrintWriter處理控制台輸出的方法:

// Demonstrate PrintWriter

import java.io.*;

public class PrintWriterDemo {

public static void main(String args[]) {

PrintWriter pw = new PrintWriter(System.out, true);

pw.println("This is a string");

int i = -7;

pw.println(i);

double d = 4.5e-7;

pw.println(d);

}

}

該程序的輸出如下:

This is a string

-7

4.5E-7

⑧ java文件輸入輸出

import java.util.*;
import java.io.*;
class Student {
private String name;
private int age;
private int javaScore;
private int cScore;

public Student(String name,int age) {
this.name = name;
this.age = age;
}

public void setJavaScore(int java) {
if(java < 101 && java >= 0) {
this.javaScore = java;
}else{
System.out.println("Wrong score !");
}

}

public int getJavaScore() {
return this.javaScore;
}

public void setCScore(int C) {
if(C < 101 && C >= 0) {
this.cScore = C;
}else{
System.out.println("Wrong score !");
}

}

public int getCScore() {
return this.cScore;
}

public String toString() {
return this.name+" "+this.age+" "+this.javaScore+" "+this.cScore+"\n";
}
}
class TestChengji {
public static void main(String [] args) throws Exception{
Student[] StudentInfo = new Student[3];
Scanner in = new Scanner(System.in);
System.out.println("請輸入學生姓名 年齡 c語言成績與java的成績,中間用空格隔開:");
System.out.println("例如: 小明 18 82 80");
for(int i=0;i<3;i++) {
System.out.println("請輸入數據:");
StudentInfo[i] = new Student(in.next(),in.nextInt());
StudentInfo[i].setCScore(in.nextInt());
StudentInfo[i].setJavaScore(in.nextInt());
}
in.close();
BufferedWriter writer = new BufferedWriter(new FileWriter("chengji.txt"));
for(int i=0;i<3;i++) {
writer.write(StudentInfo[i].toString());
writer.flush();
}
writer.close();
}
}
//試試

⑨ Java中如何實現文件的輸入和輸出

程序如下:
<span style="color:#990000;">

</span>File file1 = new File("/home/a123/a");

if (file1.exists()) {
System.out.println("存在文件夾a");
} else {
file1.mkdir(); // 文件夾的創建 創建文件夾/home/a123/a
}
File file2 = new File("/home/a123/a/test");
if (file2.exists()) {
System.out.println("存在文件夾或者文件test");
} else {
try {
file2.createNewFile(); // 文件的創建,注意與文件夾創建的區別
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/**
* 最簡單的文件讀寫方法是使用類FileWriter
* (它的父類依次是java.io.OutputStreamWriter——>java.io.Writer——>java.lang.Object );
*/

// 下面是向文件file2裡面寫數據
try {
FileWriter fileWriter = new FileWriter(file2);
String s = new String("This is a test! \n" + "aaaa");
fileWriter.write(s);
fileWriter.close(); // 關閉數據流

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

/*
* 這樣寫數據的話,是完全更新文件test裡面的內容,即把以前的東西全部刪除,重新輸入。
* 如果不想刪除以前的數據,而是把新增加的內容增添在文件末尾處。只需要在創建FileWriter對象時候,使用另外一個構造函數即可:
* FileWriter fileWriter=new FileWriter(file2,true);
*/

// 下面是從文件file2讀東西
try {
FileReader fileReader = new FileReader(file2);
String s = null;
char ch;
try {
char[] c = new char[100];
fileReader.read(c,0,2); // 具體想得到文件裡面的什麼值(單個char?int?還是String?),
System.out.println(c);
fileReader.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**
* 具體想得到文件裡面的什麼值(單個char?int?還是String?),需要知道不通read的不同用法:
* 1. int read() 讀取單個字元。
* 2. int read(char[] cbuf) 將字元讀入數組。 可以再將字元型數組轉化位字元串
* 3. int read(char[] cbuf,int off,int len) 將字元讀入數組的某一部分。
* 這三個方法都返回一個int值,作用是:讀取的字元數,如果已到達流的末尾,則返回 -1.
*/

}

⑩ java實現文件的輸入輸出的重要性是什麼

輸入和輸出功能是Java對程序處理數據能力的提高,Java以流的形式處理數據。流是一組有序的數據序列,根據操作的類型,分為輸入流和輸出流。

程序從輸入流讀取數據,向輸出流寫入數據。Java是面向對象的程序語言,每一個數據流都是一個對象,它們提供了各種支持「讀入」與「寫入」操作的流類。

閱讀全文

與java的文件輸入輸出相關的資料

熱點內容
android聊天控制項 瀏覽:128
導致壓縮機壞的原因 瀏覽:295
如何多次選取文件夾 瀏覽:280
android編譯生成odex 瀏覽:233
我的世界聯機俠伺服器如何用指令 瀏覽:94
地鐵逃生戰斗伺服器為什麼進不了 瀏覽:572
加密門卡怎麼模擬小米9 瀏覽:744
核演算法 瀏覽:631
炸彈命令 瀏覽:550
連通路徑演算法 瀏覽:349
phpemptynull 瀏覽:366
安卓手機伺服器地址在哪裡 瀏覽:428
基於單片機的多路控制器課程設計 瀏覽:65
pythonimportsys作用 瀏覽:276
騰訊雲拼團雲伺服器 瀏覽:364
海南離島將加貼溯源碼銷售嗎 瀏覽:244
linux分區讀取 瀏覽:794
單片機液晶顯示屏出現雪花 瀏覽:890
解壓器用哪個好一點 瀏覽:771
什麼app看小說全免費 瀏覽:503