Java File IO

From PeformIQ Upgrade
Revision as of 06:49, 17 October 2021 by PeterHarding (talk | contribs) (Created page with " Some examples from - http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file <pre> private String readFile( String file ) throws IO...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Some examples from - http://stackoverflow.com/questions/326390/how-to-create-a-java-string-from-the-contents-of-a-file

private String readFile( String file ) throws IOException {
    BufferedReader reader = new BufferedReader( new FileReader (file));
    String         line = null;
    StringBuilder  stringBuilder = new StringBuilder();
    String         ls = System.getProperty("line.separator");

    while( ( line = reader.readLine() ) != null ) {
        stringBuilder.append( line );
        stringBuilder.append( ls );
    }

    return stringBuilder.toString();
}
static String readFile(String path, Charset encoding) throws IOException {
  byte[] encoded = Files.readAllBytes(Paths.get(path));
  return new String(encoded, encoding);
}
List<String> lines = Files.readAllLines(Paths.get(path), encoding);
String content = readFile("test.txt", StandardCharsets.UTF_8);
String content = readFile("test.txt", Charset.defaultCharset());

IOUtils.java under Apache Licence 2.0

public static long copyLarge(InputStream input, OutputStream output) throws IOException {
   byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
   long count = 0;
   int n = 0;
   while (-1 != (n = input.read(buffer))) {
       output.write(buffer, 0, n);
       count += n;
   }
   return count;
}
String text = new Scanner( new File("poem.txt"), "UTF-8" ).useDelimiter("\\A").next();


private String readFile(String pathname) throws IOException {

    File file = new File(pathname);
    StringBuilder fileContents = new StringBuilder((int)file.length());
    Scanner scanner = new Scanner(file);
    String lineSeparator = System.getProperty("line.separator");

    try {
        while(scanner.hasNextLine()) {        
            fileContents.append(scanner.nextLine() + lineSeparator);
        }
        return fileContents.toString();
    } finally {
        scanner.close();
    }
}