java控制檯輸入和文件讀入寫出

在很多公司的筆試中都會有這樣的操作,但是一般的java書籍對控制檯讀入沒有詳細的介紹,現在規範的將控制檯輸入和文件讀入一起整理在此,方便以後查看。

 

控制檯錄入:

 

 首先,java.util.Scanner包中的Scanner(中文意思是掃描儀)類,這個類是一個final類繼承於object類,從它的類名上就可以看出它有點類似於掃描儀,所以它只能掃描用戶輸入到屏幕上的信息,這是就需要一個System.in然後再掃描。當然它掃描到的只是字符,但在需要時可以轉換成其他類型,它提供了很多此類的方法:String next()、 BigDecimal nextBigDecimal() 、BigInteger nextBigInteger() 、BigInteger nextBigInteger(int radix) 、 boolean nextBoolean() 、byte nextByte() 、 byte nextByte(int radix) 、double nextDouble() 、float nextFloat() 、int nextInt() 、int nextInt(int radix) 、 String nextLine() 、long nextLong() 、long nextLong(int radix) 、short nextShort() 、short nextShort(int radix) 。這些方法都可以得到相應類型的數據。例

  如:

  import java.util.Scanner;

  public class Importtext {

  public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);

  int i = sc.nextInt();

  System.out.println(i);

  }

  }

再有就是這個BufferedReader類,這個類“從字符輸入流中讀取文本,緩衝各個字符,從而提供字符、數組和行的高效讀取”(摘自Java幫助文檔)。類似的它讀的也是字符串,需要是進行處理,即將字符串轉換成整型、浮點型等類型。類型轉換有Integer.parseInt()Float.parseFloat(),舉個例子吧:

  import java.io.*;

  public class importtext {

  public static void main(String[] args) {

  String st;

  int num;

  float fnum;

  try{

  System.out.print("輸入:");

  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

  st = br.readLine();

  System.out.print("輸入一個數:");

  num = Integer.parseInt(br.readLine());

  System.out.print("輸入一個浮點數:");

  fnum = Float.parseFloat(br.readLine());

  System.out.print("輸出:"+st+'\n');

  System.out.print("輸出:"+num+'\n');

  System.out.print("輸出:"+fnum+'\n');

  }catch(IOException e){}

  }

  }

 

文件讀入:

/**
     * 以行爲單位讀取文件,常用於讀面向行的格式化文件
     
*/
    
public static void readFileByLines(String fileName) {
        File file 
= new File(fileName);
        BufferedReader reader 
= null;
        
try {
            System.out.println(
"以行爲單位讀取文件內容,一次讀一整行:");
            reader 
= new BufferedReader(new FileReader(file));
            String tempString 
= null;
            
int line = 1;
            
// 一次讀入一行,直到讀入null爲文件結束
            while ((tempString = reader.readLine()) != null) {
                
// 顯示行號
                System.out.println("line " + line + "" + tempString);
                line
++;
            }
            reader.close();
        } 
catch (IOException e) {
            e.printStackTrace();
        } 
finally {
            
if (reader != null) {
                
try {
                    reader.close();
                } 
catch (IOException e1) {
                }
            }
        }
    }

 

   /**
     * B方法追加文件:使用FileWriter
     
*/
    
public static void appendMethodB(String fileName, String content) {
        
try {
            
//打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
        } 
catch (IOException e) {
            e.printStackTrace();
        }
    }

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章