1. 程式人生 > >java按位元組方式讀檔案

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