JAvaファイルノートの読み書き



コードコメントを参照:
 
後ろにUTF-8のエンコードファイルを読み書きする方法があります.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

public class IOHelper {

	public static void copy(Reader in, Writer out) throws IOException {
		int c = -1;
		while ((c = in.read()) != -1) {
			out.write(c);
		}
	}
	
	/**
	 *       
	 * 
	 * @param file
	 *              
	 */
	public static String readFile(File file) throws IOException {
		Reader in = new FileReader(file);
		StringWriter out = new StringWriter();
		copy(in, out);
		return out.toString();
	}
	
	/**
	 *       
	 * 
	 * @param file
	 *              
	 */
	public static void saveFile(File file, String content) throws IOException {
		Writer writer = new FileWriter(file);
		writer.write(content);
		writer.close();
	}

	/**
	 *           ,         ,   、  、     。
	 * 
	 * @param fileName
	 *                
	 */
	public static void readFileByBytes(String fileName) {
		File file = new File(fileName);
		InputStream in = null;
		try {
			System.out.println("            ,       :");
			//        
			in = new FileInputStream(file);
			int tempbyte;
			while ((tempbyte = in.read()) != -1) {
				System.out.write(tempbyte);
			}
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		try {
			System.out.println("            ,       :");
			//        
			byte[] tempbytes = new byte[100];
			int byteread = 0;
			in = new FileInputStream(fileName);
			//             ,byteread         
			while ((byteread = in.read(tempbytes)) != -1) {
				System.out.write(tempbytes, 0, byteread);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
				}
			}
		}
	}

	/**
	 *           ,      ,        
	 * 
	 * @param fileName
	 *               
	 */
	public static void readFileByChars(String fileName) {
		File file = new File(fileName);
		Reader reader = null;
		try {
			System.out.println("            ,       :");
			//        
			reader = new InputStreamReader(new FileInputStream(file));
			int tempchar;
			while ((tempchar = reader.read()) != -1) {
				//   windows ,rn         ,      。
				//              ,     。
				//   ,   r,    n。  ,        。
				if (((char) tempchar) != 'r') {
					System.out.print((char) tempchar);
				}
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			System.out.println("            ,       :");
			//        
			char[] tempchars = new char[30];
			int charread = 0;
			reader = new InputStreamReader(new FileInputStream(fileName));
			//             ,charread        
			while ((charread = reader.read(tempchars)) != -1) {
				//      r   
				if ((charread == tempchars.length)
						&& (tempchars[tempchars.length - 1] != 'r')) {
					System.out.print(tempchars);
				} else {
					for (int i = 0; i < charread; i++) {
						if (tempchars[i] == 'r') {
							continue;
						} else {
							System.out.print(tempchars[i]);
						}
					}
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
	}

	/**
	 *          ,             
	 * 
	 * @param fileName
	 *               
	 */
	public static void readFileByLines(String fileName) {
		File file = new File(fileName);
		BufferedReader reader = null;
		try {
			System.out.println("           ,      :");
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 1;
			//       ,    null     
			while ((tempString = reader.readLine()) != null) {
				//     
				System.out.println("line " + line + ": " + tempString);
				line++;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
	}

	/**
	 *         
	 * 
	 * @param fileName
	 *               
	 */
	public static void readFileByRandomAccess(String fileName) {
		RandomAccessFile randomFile = null;
		try {
			System.out.println("          :");
			//            ,     
			randomFile = new RandomAccessFile(fileName, "r");
			//     ,   
			long fileLength = randomFile.length();
			//         
			int beginIndex = (fileLength > 4) ? 4 : 0;
			//            beginIndex  。
			randomFile.seek(beginIndex);
			byte[] bytes = new byte[10];
			int byteread = 0;
			//    10   ,        10   ,       。
			//            byteread
			while ((byteread = randomFile.read(bytes)) != -1) {
				System.out.write(bytes, 0, byteread);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (randomFile != null) {
				try {
					randomFile.close();
				} catch (IOException e1) {
				}
			}
		}
	}

   //*****************************************************************************
	//           
	/**
	 * A      :  RandomAccessFile
	 * 
	 * @param fileName
	 *               
	 * @param content
	 *                 
	 */
	public static void appendMethodA(String fileName,

	String content) {
		try {
			//            ,     
			RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
			//     ,   
			long fileLength = randomFile.length();
			//            。
			randomFile.seek(fileLength);
			randomFile.writeBytes(content);
			randomFile.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * B      :  FileWriter
	 * 
	 * @param fileName
	 * @param content
	 */
	public static void appendMethodB(String fileName, String content) {
		try {
			//         ,           true          
			FileWriter writer = new FileWriter(fileName, true);
			writer.write(content);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//            ,            ,             :
	/**
	 *          
	 * 
	 * @param file
	 * @param data
	 * @param encoding
	 */
	public static void writeStringToFile(File file, String data, String encoding)
        throws IOException
    {
        FileOutputStream fos  = null;
		Writer out = null;
		 try {  
	            fos = new FileOutputStream(file);
	            out = new OutputStreamWriter(fos, encoding);
	            out.write(data);
	            out.close();
	            fos.close();
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }finally{
	        	if(fos != null){
	        		try {  
	        			fos.close();  
	                } catch (IOException e1) {  
	                }  
	        	}
	        	if(out != null){
	        		try {  
	        			out.close();  
	                } catch (IOException e1) {  
	                }  
	        	}
	        }
    }
    /**
	 *          
	 * 
	 * @param file
	 * @param encoding
	 */
    public static String readFileToString(File file, String encoding)
        throws IOException
    {
        BufferedReader reader = null; 
        FileInputStream fInStream = null;
        StringBuffer result = new StringBuffer();
        try {  
        	fInStream = new FileInputStream(file);
            reader = new BufferedReader(new InputStreamReader(fInStream, "UTF-8"));  
            String tempString = null;  
            while ((tempString = reader.readLine()) != null) {  
                result.append(tempString);
            }  
            fInStream.close();
            reader.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
        	if(fInStream != null) {
        		try {  
        			fInStream.close();  
                } catch (IOException e1) {  
                }  
        	}
            if (reader != null) {  
                try {  
                    reader.close();  
                } catch (IOException e1) {  
                }  
            }  
        } 
        return result.toString();
    }
}