Skip to content

Instantly share code, notes, and snippets.

@FreeFly19
Created April 13, 2016 19:17
Show Gist options
  • Select an option

  • Save FreeFly19/b781f41264eb2702573a3c3161e2406e to your computer and use it in GitHub Desktop.

Select an option

Save FreeFly19/b781f41264eb2702573a3c3161e2406e to your computer and use it in GitHub Desktop.
Java IO wrappers examples
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