java第九章輸入輸出文件練習,Java文件輸入輸出

本文目錄一覽:

java中讀入和輸出文本文件

寫文件

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStreamWriter;

import java.io.UnsupportedEncodingException;

import java.io.Writer;

public class WriteFile {

    public static void main(String[] args) {

        File file = new File(“F:” + File.separator + “abcd.txt”);

        try {

            // 注意,這個地方,那個true的參數,代表如果這個文件已經存在了,就把新的內容添加到該文件的最後

            // 如果你想重新創建新文件,把true改成false就好了

            Writer writer = new OutputStreamWriter(new FileOutputStream(file, true), “GBK”);

            StringBuilder builder = new StringBuilder();

            for (int i = 0; i  100; i++) {

                int temp = (int) ((Math.random() + 1) * 1000);

                builder.append(String.valueOf(temp));

                builder.append(“|”);

                temp = (int) ((Math.random() + 1) * 1000);

                builder.append(String.valueOf(temp)).append(“\n”);

            }

            writer.write(builder.toString());

            writer.close();

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

讀文件

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStreamReader;

public class ReadFile {

    public static void main(String[] args) {

        File file = new File(“F:” + File.separator + “abcd.txt”);

        String s = “”;

        try {

            InputStreamReader read = new InputStreamReader(new FileInputStream(file), “GBK”);

            BufferedReader reader = new BufferedReader(read);

            String line;

            while ((line = reader.readLine()) != null) {

                s += line + “\n”;

            }

            reader.close();

            read.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

        System.out.println(s);

    }

}數據的格式:

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

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

public class txttest {

    /**

     * 讀取txt文件的內容

     * @param file 想要讀取的文件對象

     * @return 返迴文件內容

     */

    public static String txt2String(File file){

        String result = “”;

        try{

            BufferedReader br = new BufferedReader(new FileReader(file));//構造一個BufferedReader類來讀取文件

            String s = null;

            while((s = br.readLine())!=null){//使用readLine方法,一次讀一行

                result = result + “\n” +s;

            }

            br.close();    

        }catch(Exception e){

            e.printStackTrace();

        }

        return result;

    }

    

    public static void main(String[] args){

        Scanner scan = new Scanner(System.in);

        System.out.println(“請輸入文件名:”);

        String str = scan.next();

        String mulu = “C:\\Users\\hp\\Desktop\\” + str + “.txt”;//文件具體目錄

        File file = new File(mulu);

        System.out.println(txt2String(file));

    }

}

java題目:編寫一個程序使用java的輸入,輸出流技術將一個文本文件內容按行讀出,,

import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

/**

*

* @author Felly

* @date 2008年12月29日16:16:12

*

*/

public class InOut {

//調試的時候文件和class文件在同目錄,不然自己加絕對路徑

public final static String inFile=”in.txt”;//被寫文件

public final static String outFile=”out.txt”;//被讀文件

public void readAndWrite(String in,String out) throws

FileNotFoundException,IOException {

File inFile=new File(in);

File outFile=new File(out);

BufferedReader reader=new BufferedReader(new FileReader(outFile));

PrintWriter pw=new PrintWriter(new FileWriter(inFile));

String line=””;

int index=0;

while((line=reader.readLine())!=null)//循環到沒有內容為止

{ index++;

line=index+line;//加上行號

pw.write(line);//寫入一行

}

//close

pw.close();

reader.close();

}

}

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

程序如下:

span style=”color:#990000;”

/spanFile 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 文件輸入輸出 的編程題

就是輸入5個0 到100的數然後存入文件嘛。

代碼如下:

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Scanner;

public class Test {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

File file = new File(“c:\\1.txt”);

FileWriter fw = null;

int count = 0;

try {

fw = new FileWriter(file);

while(true){

System.out.print(“輸入第[ “+ (count + 1) +” ]個學生成績(0~100): “);

int temp = sc.nextInt();

if(temp = 100  temp = 0){

count++;

fw.write(String.valueOf(temp));

fw.write(“\r\n”);

fw.flush();

}else{

System.out.println(“輸入的數不在範圍之內,重新輸入.”);

continue;

}

if(count == 5){

System.out.println(“輸入結束.”);

break;

}

}

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}finally{

if(fw != null){

try {

fw.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

}

程序運行結束後會在C盤生成1.txt 裡面保存的5個學生的成績:

java輸入輸出問題(回答完整的追加500分)

舉一個例子吧:

利用文本編輯軟體輸入學生姓名、各課程的成績,編程讀取文件中的內容,計算每個同學的平均成績,然後輸出並保存包括平均成績的成績表。文件student內容:

0521020146 80 70 65 69 67

0521020147 90 70 65 92 56

0521020148 93 70 65 83 56

說明:

文本文件中的學生成績可以逐行逐行處理

可以利用StringTokenizer抽取每行信息中的學號以及各課成績,對於成績需要使用Integer類的parseInt方法將字元串轉換成整型量。或使用Integer類的intValue方法返回一個整型量。

使用兩個文件進行輸入與輸出,如果要求將計算平均值後的內容存放到原來文件,一種簡單的方法是利用File類刪除student文件,然後將student1文件重命名為student文件,最後刪除student1文件。

程序代碼如下:

import java.io.*;

import java.util.*;

public class ch8ex7{

public static void main(String[]args){

try{

PrintWriter outputStream=new PrintWriter(new FileOutputStream(“student1.txt”));

BufferedReader inputStream=new BufferedReader(new FileReader(“student.txt”));

StringTokenizer t;

int score[]=new int[4];

int index;

int accumulateScore;

double average;

String line=inputStream.readLine();

while(line!=null){

t=new StringTokenizer(line);

String studentID=t.nextToken();

accumulateScore=0;

index=0;

while(t.hasMoreTokens()){

Integer sc=new Integer(t.nextToken());

score[index]=sc.intValue();

accumulateScore=accumulateScore+score[index];

index++;

}

average=accumulateScore/4.0;

String out;

out=studentID+” “;

for(index=0;index4;index++)

out=out+score[index]+” “;

out=out+average;

outputStream.println(out);

line=inputStream.readLine();

}

outputStream.close();

inputStream.close();

}catch(Exception e){

System.out.println(e.getMessage());

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/200155.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-05 14:03
下一篇 2024-12-05 14:03

相關推薦

  • vue下載無後綴名的文件被加上後綴.txt,有後綴名的文件下載正常問題的解決

    本文旨在解決vue下載無後綴名的文件被加上後綴.txt,有後綴名的文件下載正常的問題,提供完整的代碼示例供參考。 一、分析問題 首先,需了解vue中下載文件的情況。一般情況下,我們…

    編程 2025-04-29
  • 如何在Java中拼接OBJ格式的文件並生成完整的圖像

    OBJ格式是一種用於表示3D對象的標準格式,通常由一組頂點、面和紋理映射坐標組成。在本文中,我們將討論如何將多個OBJ文件拼接在一起,生成一個完整的3D模型。 一、讀取OBJ文件 …

    編程 2025-04-29
  • 為什麼用cmd運行Java時需要在文件內打開cmd為中心

    在Java開發中,我們經常會使用cmd在命令行窗口運行程序。然而,有時候我們會發現,在運行Java程序時,需要在文件內打開cmd為中心,這讓很多開發者感到疑惑,那麼,為什麼會出現這…

    編程 2025-04-29
  • Python中讀入csv文件數據的方法用法介紹

    csv是一種常見的數據格式,通常用於存儲小型數據集。Python作為一種廣泛流行的編程語言,內置了許多操作csv文件的庫。本文將從多個方面詳細介紹Python讀入csv文件的方法。…

    編程 2025-04-29
  • Python程序文件的拓展

    Python是一門功能豐富、易於學習、可讀性高的編程語言。Python程序文件通常以.py為文件拓展名,被廣泛應用於各種領域,包括Web開發、機器學習、科學計算等。為了更好地發揮P…

    編程 2025-04-29
  • Python將矩陣存為CSV文件

    CSV文件是一種通用的文件格式,在統計學和計算機科學中非常常見,一些數據分析工具如Microsoft Excel,Google Sheets等都支持讀取CSV文件。Python內置…

    編程 2025-04-29
  • Python zipfile解壓文件亂碼處理

    本文主要介紹如何在Python中使用zipfile進行文件解壓的處理,同時詳細討論在解壓文件時可能出現的亂碼問題的各種解決辦法。 一、zipfile解壓文件亂碼問題的根本原因 在P…

    編程 2025-04-29
  • Python如何導入py文件

    Python是一種開源的高級編程語言,因其易學易用和強大的生態系統而備受青睞。Python的import語句可以幫助用戶將一個模塊中的代碼導入到另一個模塊中,從而實現代碼的重用。本…

    編程 2025-04-29
  • Python合併多個相同表頭文件

    對於需要合併多個相同表頭文件的情況,我們可以使用Python來實現快速的合併。 一、讀取CSV文件 使用Python中的csv庫讀取CSV文件。 import csv with o…

    編程 2025-04-29
  • Python寫文件a

    Python語言是一種功能強大、易於學習、通用並且高級編程語言,它具有許多優點,其中之一就是能夠輕鬆地進行文件操作。文件操作在各種編程中都佔有重要的位置,Python作為開發人員常…

    編程 2025-04-29

發表回復

登錄後才能評論