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();
        }
    }

 

 

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