package FileOp;import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;import javax.swing.JOptionPane;public class FileDemo {
public static void main(String[] args) {

///////读文件
File file = new File("e:/a.txt");
FileInputStream inputfile = null;
StringBuffer str= new StringBuffer(" ");
try{
inputfile = new FileInputStream(file);
} catch(FileNotFoundException fe) {
fe.printStackTrace();
}
int readbytes;
try{
while((readbytes = inputfile.read())!=-1){
str.append((char)readbytes);
}
}catch (IOException e) {
e.printStackTrace();
}
System.out.print(str);
try{
inputfile.close();
}catch(IOException e) {
e.printStackTrace();
}


///写文件
File fOut = new File("e:/b.txt");
FileOutputStream outStream=null;
try{
outStream = new FileOutputStream(fOut);
}catch(FileNotFoundException fe) {
fe.printStackTrace();
}

try{
outStream.write("abcdefg".getBytes());
}catch(IOException ioe) {
ioe.printStackTrace();
}
try{
outStream.close();
}catch(IOException e){
e.printStackTrace();
}
}
}

解决方案 »

  1.   

    上面的处理中文会乱码,用这个吧。
    package FileOp;import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.IOException;import javax.swing.JOptionPane;public class FileDemo {
    public static void main(String[] args) {

    ///////读文件
    File file = new File("e:/a.txt");
    FileInputStream inputfile = null;
    StringBuffer str= new StringBuffer(" ");
    try{
    FileReader readIn = new FileReader(file);
    int size = (int)file.length();
    int charsRead=0;
    char content[] = new char[size];
    while(readIn.ready())
    charsRead +=readIn.read(content, charsRead, size-charsRead);
    readIn.close();
    System.out.print(new String(content, 0, charsRead));
    try{
    readIn.close();
    }catch(IOException e) {
    e.printStackTrace();
    }
    }catch(IOException exx) {
    exx.printStackTrace();
    }


    ///写文件
    File fOut = new File("e:/b.txt");
    FileOutputStream outStream=null;
    try{
    outStream = new FileOutputStream(fOut);
    }catch(FileNotFoundException fe) {
    fe.printStackTrace();
    }

    try{
    outStream.write("abcdefg".getBytes());
    }catch(IOException ioe) {
    ioe.printStackTrace();
    }
    try{
    outStream.close();
    }catch(IOException e){
    e.printStackTrace();
    }
    }
    }