如题所述
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamTest1
{
public static void main(String[] args)
{
try
{
File file=new File("F:\\io\\abc.txt");
FileInputStream fis=new FileInputStream(file);
int first=fis.read();
System.out.print("文件中第一个字节是:"+first+"字符形式为:"+(char)first);
int b=0;
while((b=fis.read())!=-1)
{
System.out.print((char)b+" ");
}
fis.close();
}
catch (FileNotFoundException e)
{
System.out.println("操作的文件不存在");
}
catch(IOException e)
{
System.out.println("发生IO操作异常");
}
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamTest1<img id="selectsearch-icon" src="搜索">
{
public static void main(String[] args)
{
try
{
File file=new File("F:\\io\\abc.txt");
FileInputStream fis=new FileInputStream(file);
int first=fis.read();
System.out.print("文件中第一个字节是:"+first+"字符形式为:"+(char)first);
int b=0;
while((b=fis.read())!=-1)
{
System.out.print((char)b+" ");
}
fis.close();
}
catch (FileNotFoundException e)
{
System.out.println("操作的文件不存在");
}
catch(IOException e)
{
System.out.println("发生IO操作异常");
}
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamTest1
{
public static void main(String[] args)
{
try
{
File file=new File("F:\\io\\abc.txt");
FileInputStream fis=new FileInputStream(file);
int first=fis.read();
System.out.print("文件中第一个字节是:"+first+"字符形式为:"+(char)first);
int b=0;
while((b=fis.read())!=-1)
{
System.out.print((char)b+" ");
}
fis.close();
}
catch (FileNotFoundException e)
{
System.out.println("操作的文件不存在");
}
catch(IOException e)
{
System.out.println("发生IO操作异常");
}
}
}
首先,我以往经验是写入字节流和输出字节流的方式一定要一致,不然写入的字节流就会出错甚至读取不到,下面是字节流的写入和读取方法:
class Test{
public static void main(String args[]){
FileInputStream fis = null;
FileOutputStream fos = null;
byte[] buffer = new byte[100];
int temp = 0;
try{
fis = new FileInputStream("D:/wenhao/src/from.txt");
fos = new FileOutputStream("D:/wenhao/src/to.txt");
while(true){
temp = fis.read(buffer,0,buffer.length);
if(temp == -1){
break;
}
fos.write(buffer,0,temp);
}
}
catch(Exception e){
System.out.println(e);
}
finally{
try{
fis.close();
fos.close();
}
catch(Exception e2){
System.out.println(e2);
}
}
}
}