JAVA菜鸟入门(1) ReadFile

来源:互联网 发布:淘宝关键词怎么写 编辑:程序博客网 时间:2024/05/17 01:05

最近要开始积极地从C++切换到JAVA上了,大家都说基本可以平滑切换。 

目前试了试,主要的问题还是语法表达还不够习惯的问题。所以用这个系列来做一些记录吧。

这个代码读入一组数据,然后将这组数据转化为2进制表达的字符串,输出出来。

eg. 读入input. txt。其中input.txt包含一行, 1,3,6,8。那么输出为

1->1010
3->101
6->11
8->1001


代码如下:

注释中特别写了一些从C++和JAVA的区别,以及JAVA应该注意的问题。

import java.io.*;public class SimpleCal  {        String Cal(int i) {            i = (3*i + 7)%11;            String result = Integer.toBinaryString(i);            return result;        }        public static void main(String args[]) { // NOTE 命令行参数写法            if (args.length < 1 ) { //NOTE 判断命令行参数的个数。另外java中args是不包括程序本身的。所以如果args从0开始计算。而C++中的命令行参数包括程序本身,所以argc从1开始计算。                System.out.println("There should be one parameter.");                  return;            }            SimpleCal sc = new SimpleCal(); //生成当前类SimpleCal的对象,等会儿在当前的main函数中使用。            BufferedReader in; //读文件的类。            String str;            String arr[]; //字符串数组            int intarr[]; //整数数组            int tmp;            try { //①读文件的整个流程使用try {...}catch(){...}包裹。如果没写try catch,编译将报错。                in = new BufferedReader(new FileReader(args[0])); //②第一层,FileReader,第二层BufferedReader。                while ((str = in.readLine()) !=  null) { //③固定搭配: 用readLine()读一行到String.                    System.out.println("\n\n" + str);                     arr = str.split(",");//④把读的一行进行tokenize, 结果放入String[] array中。                    for (String each : arr) { //⑤类似for each 语句,变量声明String each必须在括号中完成,提到前面会报错。                        each = each.replaceAll(" +", ""); //⑥replaceAll去掉头尾空格。                        tmp = Integer.parseInt(each); //⑦String To Int                        System.out.format("%d->%s\n",tmp, sc.Cal(tmp)); //⑧格式化输出。                    }                }            } catch (IOException e) { //异常: IOException                System.out.println("IO file Exeption");             }        }}



读文件的一个常见方法:

BufferedReader br = new BufferedReader(new FileReader(file));String line;while ((line = br.readLine()) != null) {   // process the line.}br.close();


以后使用到更多其它读文件的方法的时候再做更新。

0 0