java文件输入与输出_Java 文件的输入输出基本操作

一. 文件的获取和写入

1. 文件的读取

File InputFile = New File(“input.txt”); //先用file类读取文件

Scanner in = new Scanner(inputFile) //接着用file的对象生成一个scanner对象

(Scanner in = new Scanner(new File(“input.txt”)); //生成scanner对象的另一种方式)

2. 文件的写入

PrintWriter out = new PrintWriter(“output.txt”);

out.println(“Hello World”);

out.printf(“Total: %8.2f\n”, total);

3. 关闭读取(Scanner)和写入(PrintWriter)的对象

in.close();

out.close();

4. 读取网页内容

String address = “http://horstmann.com/index.html”;

URL pageLocation = new URL(address);

Scanner in = new Scanner(pageLocation.openStream());

5. 输入输出流读取文件(比如图片)

URL p_w_picpathLocation = new URL(“http://horstmann.com/java4everyone/duke.gif”); //输入流

InputStream in = p_w_picpathLocation.openSream();

FileOutputStream out = new FileOutPutStream(“duke.gif”); //输出流

Boolean done = false;

while(!done){

int input = in.read();

if(input == -1){ done = true;}

else{ out.write(input); }

}

二. 文件内容的读取

1. 读一个字符(用useDelimiter方法)

Scanner in = new Scanner(…) ;

in.useDelimiter(“”);

//获取字符

while(in.hasNext()){

char ch = in.next().charAt(0);

Process ch.

}

注:分析字符类型的几个方法:isDigit(), isLetter(), isUpperCase(), isLowerCase(),isWhileSpace()

2. 读整个单词

while(in.hasNext()){

Sring input = in.next();

System.out.println(input);

}

注:next 方法读一个被while space分开的 string (while spaces 包括:spaces , tab characters和 newline characters)

如果整个文件不包含任何字符,抛出 “no such element exception”

3. 读一整行

String line = in.nextLine();

//用hasNextLine方法来判断是否有下一行可以读取

while(in.hasNextLine()){

String line = nextLine();

Process line.

}

4. 数字 单词 和行的混合读取

因为nextInt(),nextDouble() 和 next ()方法不读取(whilespace),因此在混合调用 nextInt()/nextDouble()/next() 和nextLine()方法时, 要调用nextline()方法读取换行符“/n“

例. 有下面数据:

China

1330044605

India

114995898

United Stated

3038246462

while(in.hasNextLine()){

String countryName = in.nextLine();

int population = in.nextInt();

in.nextLine();

Procees the country name and population

}

三. 内容的格式输出

格式输出需遵循的架构:第一个字符是%

选择一个标志符修改格式(可选,见表1)

规定输出的宽度

规定输出类型(见表2)

参考文献

Cay.S. Horstmann(2012). BIG JAVA Late Objects.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值