Created
April 13, 2016 19:17
-
-
Save FreeFly19/b781f41264eb2702573a3c3161e2406e to your computer and use it in GitHub Desktop.
Java IO wrappers examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.io.FileInputStream; | |
| import java.io.FileNotFoundException; | |
| import java.io.FileOutputStream; | |
| import java.io.IOException; | |
| /** | |
| * Created by FreeFly on 13.04.2016. | |
| */ | |
| public class IOExample { | |
| public static void main(String[] args) throws FileNotFoundException { | |
| System.out.println(readTextFromFile("D:\\file.txt")); | |
| writeTextFromFile("D:\\file.txt", "Some new Text"); | |
| } | |
| public static String readTextFromFile(String filePath) { | |
| String res = ""; | |
| try { | |
| FileInputStream fileInputStream = new FileInputStream(filePath); | |
| int oneChar; | |
| while ((oneChar = fileInputStream.read()) != -1) { | |
| res += (char)oneChar; | |
| } | |
| } catch (FileNotFoundException e) { | |
| System.out.println("File not found."); | |
| } catch (IOException e) { | |
| System.out.println("Some Input/Output exception."); | |
| } | |
| return res; | |
| } | |
| public static void writeTextFromFile(String filePath, String text) { | |
| try { | |
| FileOutputStream fileOutputStream = new FileOutputStream(filePath); | |
| fileOutputStream.write(text.getBytes()); | |
| } catch (FileNotFoundException e) { | |
| System.out.println("File not found."); | |
| } catch (IOException e) { | |
| System.out.println("Some Input/Output exception."); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment