sentence stringlengths 1 1.38k | label stringclasses 3
values |
|---|---|
How to create a Java String from the contents of a file? | o |
I've been using this idiom for some time now. | o |
And it seems to be the most wide-spread, at least in the sites I've visited. | p |
Does anyone have a better/different way to read a file into a string in Java? | o |
CODESNIPPET_JAVA1 . | o |
Can anyone explain me in a very simple way what's with the NIO? | o |
Each time I read about itI get lost in the nth mention of channel :(. | n |
do remember that it's not guaranteed that the line separator in the file isn't necessary the same as the system's line separator. | o |
Could you please insert a proper try finally that closes the reader? | o |
Someone might actually use this example and introduce a bug into his code. | n |
Code above has a bug of adding extra new line char at the last line.It should be something like followingif(line
reader.readLine() ) != null){ stringBuilder.append( line );}while (line
reader.readLine() ) != null) { stringBuilder.append( ls ); stringBuilder.append( line );}. | n |
Java 7 introduces byte[] Files.readAllBytes(file); To those, who suggest the 'one-line' Scanner solution: Don't yo need to close it? | o |
Read text from a file Here's a compact, robust idiom for Java 7, wrapped up in a utility method: CODESNIPPET_JAVA1 . | p |
Memory utilization This method can temporarily require memory several times the size of the file, because for a short time the raw file contents (a byte array), the decoded characters (a character buffer), and a copy of the character data (in the new CODETERM1 instance) all reside in memory at once. | n |
It is safest to apply to files that you know to be small relative to the available memory. | n |
For reading large files, you need a different design for your program, one that reads a chunk of text from a stream, processes it, and then moves on to the next, reusing the same fixed-sized memory block. | n |
Here, "large" depends on the computer specs. | o |
Nowadays, this threshold might be many gigabytes of RAM. | o |
Character encoding One thing that is missing from the sample in the original post is the character encoding. | o |
There are some special cases where the platform default is what you want, but they are rare, and you should be able justify your choice. | p |
The URL_http://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardChar sets.html [CODETERM2] class define some constants for the encodings required of all Java runtimes: CODESNIPPET_JAVA2 . | o |
The platform default is available from URL_http://docs.oracle.com/javase/7/doc s/api/java/nio/charset/Charset.html#defaultCharset%28%29 [the-CODETERM3-class] itself: CODESNIPPET_JAVA3 . | o |
Note: This answer largely replaces my Java 6 version. | o |
The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. | p |
You can view the old version via the "edited" link on this answer. | o |
Quite interesting. | p |
What does the channel means. | o |
I know that is to avoid block the "thread? | o |
" They can be bidirectional ( or that's what I understood ) But, in more simple word, what are they? | o |
Can you elaborate further? | o |
In many ways, a ReadableByteChannel is like an InputStream, and WritableByteChannel is like an OutputStream. | o |
Many concrete Channels implement both of these interfaces, so one object is bi-directional. | o |
Some channels (SocketChannel) support non-blocking IO, but this isn't true of all channels. | o |
Do you know the time- and memory-efficiencies of this idiom, or can at least estimate? | o |
It's a beautiful idiom!. | p |
Technically speaking, it's O(n) in time and space. | o |
Qualitatively, due the immutability requirement of Strings, it's pretty hard on memory; temporarily there are two copies of the char data in memory, plus the room for the encoded bytes. | n |
Assuming some single-byte encoding, it will (temporarily) require 5 bytes of memory for each character in the file. | n |
Since the question asks specifically for a String, that's what I show, but if you can work with the CharBuffer returned by "decode", the memory requirement is much less. | n |
Time- wise, I don't think you'll find anything faster in the core Java libs. | p |
Possible typo? | o |
NIO has a Charset (not CharSet) class called java.nio.charset.Charset. | o |
Is this what CharSet should have been? | o |
Note : after exercising a bit that code, I found out that you can't reliably delete the file right after reading it with this method, which may be a non issue in some case, but not mine.May it be in relation with this issue : URL_http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4715154 ?I finally went with the propos... | o |
@Sbastien Nussbaumer: I also bumped on this problem. | o |
Amazing that the bug has been marked "Will Not Fix". | n |
This essentially means that FileChannel#map is, in general, unusable. | o |
@Sbastien Nussbaumer: The bug has been deleted from the Oracle / Sun Bug Database: "This bug is not available. | n |
" Google cached the site at URL_http://webcac he.googleusercontent.com/search?q=cache:bugs.sun.com/bugdatabase/view_bug.do%3 Fbug_id%3D4715154. | o |
I tried reading an exe file using this method with default charset, append some data in it and again make it an exe, But it corrupted the exe, Any thoughts ? | o |
@smilepleeeaz What you describe makes no sense. | o |
EXE files are not text. | o |
And they have a well-defined structure. | o |
First you are destroying the content of the file by decoding it as text, then you are destroying the structure by appending text to it. | o |
How could this fail to corrupt the EXE? | o |
I don't really care about encoding, could I just use Charset.defaultCharset() instead of having an argument accepting it? | o |
@yannbane If you are sure that the file will always be encoded with the platform's default character set, yes, you could do that. | o |
If there's a mismatch, then you'll care about encoding. | o |
Commons URL_http://commons.apache.org/proper/commons-io/apidocs/org/apache/com mons/io/FileUtils.html#readFileToString%28java.io.File%29 [CODETERM1] :
CODESNIPPET_JAVA1 . | o |
Reads the contents of a file into a String using the default encoding for the VM. | o |
The file is always closed. | o |
Parameters:
CODETERM2 \- the file to read, must not be null
Returns: the file contents, never null
Throws: - CODETERM3 \- in case of an I/O error
Since: Commons IO 1.3.1
by Oscar Reyes** I've found the code used ( indirectly ) by that class: URL_http://www.docjar.com/html/api/org/apache/commons/io/IOUtils.java.h... | o |
Very similar to the one use by Ritche_W . | o |
I don't find that method in the URL you provide. | o |
It's in the class org.apache.commons.io.FileUtils. | o |
I'm using FileUtils too, but I'm wondering what is better betwwen using FileUtils or the accepted nio answer? | o |
@Guillaume: The biggest question is whether you're comfortable having a dependency on a 3rd party library. | o |
If you do have Commons IO or [Guava]( URL_http://stackoverflow.com/a/2224519/56285 ) in your project, then use that (just for code simplicity; otherwise there likely won't be a noticeable difference). | o |
From URL_http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner.html [this-page] the one-line solution: CODESNIPPET_JAVA1 . | o |
or CODESNIPPET_JAVA2 . | o |
If you want to set the charset . | o |
+1 I thought the selimeter should be \\\Z. | o |
\\\A works because there is no "other beginning of file", so you are in fact read the last token...which is also the first. | p |
Never tried with \\\Z. | o |
Also note you can read anything that is Readable , like Files, InputStreams, channels...I sometimes use this code to read from the display window of eclipse, when I'm not sure if I'm reading one file or another...yes, classpath confuses me. | n |
As the poster, I can say I really don't know if and when the file is properly close...I never write this one in production code, I use it only for tests or debug. | o |
It has a limit of 1024 chars I think. | o |
Scanner implements Closeable (it invokes close on the source) - so while elegant it shouldn't really be a one-liner. | p |
The default size of the buffer is 1024, but Scanner will increase the size as necessary (see Scanner#makeSpace()). | o |
This one fails for empty files with a java.util.NoSuchElementException. | o |
If you're looking for an alternative that doesn't involve a 3rd party library (e.g. | o |
commons IO), you can use the URL_http://java.sun.com/javase/6/docs/api/java/util/Scanner.html [Scanner] class CODESNIPPET_JAVA1 . | o |
I think this is the best way. | p |
Check out URL_http://java.sun.com/docs/books/tutorial/essential/io/scanning.html . | o |
The Scanner constructor that accepts a String doesn't treat the string as the name of a file to read, but as the text to be scanned. | o |
I make that mistake all the time. | n |
:-/. | o |
@Alan, good catch. | p |
I edited Don's answer slightly to fix that (I hope). | o |
fileContents.append(scanner.nextLine()).append(lineSeparator);. | o |
Change the initialization statement to Scanner scanner
new Scanner((Readable) new BufferedReader(new FileReader(file)));. | o |
Otherwise you may only capture part of the file. | o |
URL_http://code.google.com/p/guava-libraries/ [Guava] has a method similar to the one from Commons IOUtils that Willi aus Rohr mentioned: CODESNIPPET_JAVA1 . | o |
by Oscar Reyes** This is the (simplified) underlying code on the cited library: CODESNIPPET_JAVA2 . | o |
(by Jonik): The above doesn't match the source code of recent Guava versions. | o |
For the current source, see the classes URL_http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/io/Files.java [Files] , URL_http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/io/CharStreams.java [CharStreams] , URL_http://code.google.com/p/guava-libraries/s... | o |
This code has casting from long to int which could pop up some crazy behaviour with big files. | n |
Has extra spaces and where do you close the inputstream? | o |
@M-T-A: The stream
closed, note the use of Closer in [CharSource]( URL_http://code.google.com/p/guava - libraries/source/browse/guava/src/com/google/common/io/CharSource.java). | o |
The code in the answer isn't the actual, current Guava source. | o |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.