Reading a plain text file in Java

My favorite way to read a small file is to use a BufferedReader and a StringBuilder. It is very simple and to the point (though not particularly effective, but good enough for most cases): BufferedReader br = new BufferedReader(new FileReader(“file.txt”)); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) … Read more

Find all files in a directory with extension .txt in Python

You can use glob: import glob, os os.chdir(“/mydir”) for file in glob.glob(“*.txt”): print(file) or simply os.listdir: import os for file in os.listdir(“/mydir”): if file.endswith(“.txt”): print(os.path.join(“/mydir”, file)) or if you want to traverse directory, use os.walk: import os for root, dirs, files in os.walk(“/mydir”): for file in files: if file.endswith(“.txt”): print(os.path.join(root, file))

Correct way to write line to file?

This should be as simple as: with open(‘somefile.txt’, ‘a’) as the_file: the_file.write(‘Hello\n’) From The Documentation: Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single ‘\n’ instead, on all platforms. Some useful reading: The with statement open() ‘a’ is for append, or use ‘w’ to … Read more

How do I create a file and write to it?

Note that each of the code samples below may throw IOException. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling. Note that each of the code samples below will overwrite the file if it already exists Creating a text file: PrintWriter writer = new PrintWriter(“the-file-name.txt”, “UTF-8”); writer.println(“The first line”); … Read more

How do I create a Java string from the contents of a file?

Read all text from a file Java 11 added the readString() method to read small files as a String, preserving line terminators: String content = Files.readString(path, StandardCharsets.US_ASCII); For versions between Java 7 and 11, here’s a compact, robust idiom, wrapped up in a utility method: static String readFile(String path, Charset encoding) throws IOException { byte[] … Read more

How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

You can use a library called ExcelLibrary. It’s a free, open source library posted on Google Code: ExcelLibrary This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in. It’s very simple, small … Read more