java按字节方式读文件

java读文件
 
/* Readfile.java
读取文件的内容,并将原样输出至屏幕上
使用方法:java Readfile 文件名
*/

import java.io.*;

public class Readfile
{
public static void main(String[] args)
{
byte[] buff = new byte[1024];
boolean cont = true;
FileInputStream infile = null;

// 生成对象infile 准备读取文件
try
{
infile = new FileInputStream(args[0]);
}
catch (FileNotFoundException e)
{
System.err.println("没有找到文件");
System.exit(1);
}

while (cont)
{
try
{
int n = infile.read(buff); // 从文件读取数据
System.out.write(buff, 0, n); // 写入System.out中
}
catch (Exception e)
{
cont = false;
}
}

try
{
infile.close();
}
catch (IOException e)
{
System.err.println("文件错误");
System.exit(1);
}
}
}
java写文件
 
/* Writefile.java
接收键盘的输入,并原样输出到屏幕上
此外,还有将键盘输入的数据按顺序存放到文件中
使用方法:java Writefile 文件名
要结束此程序时,请在行的开始部分输入一个#号。
*/

import java.io.*;

// Class Writefile
public class Writefile
{
public static void main(String[] args)
{
byte[] buff = new byte[1024];
boolean cont = true; // 循环控制变量
FileOutputStream outfile = null; // 文件输出对象

// 生成对象outfile,准备输出到文件
try
{
outfile = new FileOutputStream(args[0]);
}
catch (FileNotFoundException e)
{
System.err.println("文件不存在");
System.exit(1);
}

// 行首没有输入句号时执行如下循环
while (cont)
{
try
{
int n = System.in.read(buff); // 从System.in读入数据
System.out.write(buff, 0, n); // 写入到System.out中
if (buff[0]==´#´)
{
cont = false;
}
else
{
outfile.write(buff, 0, n);
}

}
catch (Exception e)
{
System.exit(1);
}
}

// 关闭文件
try
{
outfile.close();
}
catch (IOException e)
{
System.err.println("文件错误");
System.exit(1);
}
}
}

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值