How do I check if a file exists in Java?
Using java.io.File: File f = new File(filePathString); if(f.exists() && !f.isDirectory()) { // do something }
Using java.io.File: File f = new File(filePathString); if(f.exists() && !f.isDirectory()) { // do something }
A common pattern is to use try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { // process the line. } } You can read the data faster if you assume there is no character encoding. e.g. ASCII-7 but it won’t make much difference. It is highly likely … Read more
The command you want is named tee: foo | tee output.file For example, if you only care about stdout: ls -a | tee output.file If you want to include stderr, do: program [arguments…] 2>&1 | tee outfile 2>&1 redirects channel 2 (stderr/standard error) into channel 1 (stdout/standard output), such that both is written as stdout. … Read more
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
One way to do it is: while read p; do echo “$p” done <peptides.txt As pointed out in the comments, this has the side effects of trimming leading whitespace, interpreting backslash sequences, and skipping the last line if it’s missing a terminating linefeed. If these are concerns, you can do: while IFS=”” read -r p … Read more