Determine the number of lines within a text file

Seriously belated edit: If you’re using .NET 4.0 or later The File class has a new ReadLines method which lazily enumerates lines rather than greedily reading them all into an array like ReadAllLines. So now you can have both efficiency and conciseness with: var lineCount = File.ReadLines(@”C:\file.txt”).Count(); Original Answer If you’re not too bothered about … Read more

How to determine the encoding of text

EDIT: chardet seems to be unmantained but most of the answer applies. Check https://pypi.org/project/charset-normalizer/ for an alternative Correctly detecting the encoding all times is impossible. (From chardet FAQ:) However, some encodings are optimized for specific languages, and languages are not random. Some character sequences pop up all the time, while other sequences make no sense. … Read more

How can you find and replace text in a file using the Windows command-line environment?

A lot of the answers here helped point me in the right direction, however none were suitable for me, so I am posting my solution. I have Windows 7, which comes with PowerShell built-in. Here is the script I used to find/replace all instances of text in a file: powershell -Command “(gc myFile.txt) -replace ‘foo’, … Read more

How to append text to an existing file in Java?

Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback. Java 7+ For a one-time task, the Files class makes this easy: try { Files.write(Paths.get(“myfile.txt”), “the text”.getBytes(), StandardOpenOption.APPEND); }catch (IOException e) { //exception handling left as an exercise for the reader … Read more

How do I save a String to a text file using Java?

If you’re simply outputting text, rather than any binary data, the following will work: PrintWriter out = new PrintWriter(“filename.txt”); Then, write your String to it, just like you would to any output stream: out.println(text); You’ll need exception handling, as ever. Be sure to call out.close() when you’ve finished writing. If you are using Java 7 … Read more

Why should text files end with a newline?

Because that’s how the POSIX standard defines a line: 3.206 Line A sequence of zero or more non- <newline> characters plus a terminating <newline> character. Therefore, lines not ending in a newline character aren’t considered actual lines. That’s why some programs have problems processing the last line of a file if it isn’t newline terminated. … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)