现在的位置: 首页 > 综合 > 正文

java读写文件- -

2013年10月21日 ⁄ 综合 ⁄ 共 1283字 ⁄ 字号 评论关闭

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

抱歉!评论已关闭.