Differencebetween 'File.Read' and 'Io.Read'

What is the difference between 'File.read' and 'IO.read'?

since File is a subclass of IO and it does not have the read method, when you invoke File.read, you are actually calling IO.read
no difference here.

When should I ever use file.read() or file.readlines()?

The short answer to your question is that each of these three methods of reading bits of a file have different use cases. As noted above, f.read() reads the file as an individual string, and so allows relatively easy file-wide manipulations, such as a file-wide regex search or substitution.

f.readline() reads a single line of the file, allowing the user to parse a single line without necessarily reading the entire file. Using f.readline() also allows easier application of logic in reading the file than a complete line by line iteration, such as when a file changes format partway through.

Using the syntax for line in f: allows the user to iterate over the file line by line as noted in the question.

(As noted in the other answer, this documentation is a very good read):

https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

Note:
It was previously claimed that f.readline() could be used to skip a line during a for loop iteration. However, this doesn't work in Python 2.7, and is perhaps a questionable practice, so this claim has been removed.

What is the difference between read() and readline() in python?

This question has been answered countless times, and the documentation does a good job of describing the differences, too. But here goes:

If you have a file (test.txt) like so:

first line
second line
third line

Then this code:

with open("test.txt", "r") as file:
line = file.readline()
print(line)

Will produce this output:

first line

That's because readline just reads the next line.

If you use this code instead:

with open("test.txt", "r") as file:
content = file.read()
print(content)

Output:

first line
second line
third line

read() reads the entire contents of the file into a string.
You can also give read() an optional argument, which designates the number of characters to read from the file:

with open("test.txt", "r") as file:
content = file.read(15)
print(content)

Output:

first line
seco

Finally, the third function, which you didn't mention, is readlines, which returns a list of lines (strings):

with open("test.txt", "r") as file:
lines = file.readlines()
print(lines)

Output:

['first line\n', 'second line\n', 'third line\n']

Difference between os.File, io.Reader and os.Stdin

This is because bufio.NewScanner has io.Reader as an argument.

func NewScanner(r io.Reader) *Scanner

and io.Reader is the interface that wraps the basic Read method.

type Reader interface {
Read(p []byte) (n int, err error)
}

From the os package in Golang:

Open opens the named file for reading. If successful, methods on the
returned file can be used for reading; the associated file descriptor
has mode O_RDONLY. If there is an error, it will be of type
*PathError.

func Open(name string) (file *File, err error)

The returned value *os.File implements io.Reader.

So whetever implements Reader interface can be passed as an argument to any method has io.Reader as an argument.

What the difference between read() and read1() in Python?

In short, read([size]) ensures it reads size bytes (or until EOF) and it may involve multiple reads on the underlying IO object if necessary.

read1([size]) is to get any data (at-most size bytes) that is available in the buffer. If no data in buffer then do at-most 1 read() to the IO object.

To elaborate:

read([size]): if size is negative or None, calls the underlying raw stream's readall() method which would read until the EOF is reached or it's going to block in a non-blocking mode. The underlying raw stream is duck-typed, meaning if it does not have a readall(), then multiple calls to raw stream's read() is made until EOF is reached or it would block.

if the size is a positive, read() would return the available data from the buffer. If the available data is less than the size, then multiple read() calls are made to the raw stream until size bytes are available or EOF is reached.

read1([size]) on the other hand returns any data that is available on the buffer even if it less than size, If no data is available and size is > 0, then it makes at most one read() call to the underlying IO object.

if size is omitted or < 0, then the size of available buffer is used, So no read() call performed on the raw stream in this case.

Read and Write from files Java

You can use FileInputStream and FileOutputStream to do so..

Hope this will serve your purpose

import java.util.Scanner;
import java.io.*;

public class MainClass {

public static void main(String[] args) throws IOException {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream("IN File");
outputStream = new FileOutputStream("OUT File");
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
byte[] strToBytes = line.getBytes();
outputStream.write(strToBytes);
outputStream.write(System.getProperty("line.separator").getBytes());
}
// note that Scanner suppresses exceptions
if (sc.ioException() != null) {
throw sc.ioException();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
}
}

What is the difference between Java File+Scanner object for reading files and a FileReader object?

In simple words:

Scanner: A simple text scanner which can parse primitive types and strings using regular expressions. The advantage is programmers need to not worry about the writing implementation for parsing and converting the input data to various primitives. This fastens the development and reliable, because it is used by everybody and gets tested.

FileReader: Convenience class for reading character files or stream of characters. The functionality provided by FileReader is very limited to just reading the chars from the defined stream. The rest of the work has to be done the programmer.

Conclusion: The Scanner provide reliable and easy to use implementations for reading and parsing the streams (files), saves a lot of time in development.

what is difference between file reading and streaming?

First thing is fileread is fully buffered method. and streaming is partial buffered method.

Now what does it mean?

Fully buffered function calls like readFileSync() and readFile() expose
the data as one big blob. That is, reading is performed and then the full set of data is returned either in synchronous or asynchronous fashion.
With these fully buffered methods, we have to wait until all of the data is read, and internally Node will need to allocate enough memory to store all of the data in memory. This can be problematic - imagine an application that reads a 1 GB file from disk. With only fully buffered access we would need to use 1 GB of memory to store the whole content of the file for reading - since both readFile and readFileSync return a string containing all of the data.

Partially buffered access methods are different. They do not treat data input as a discrete event, but rather as a series of events which occur as the data is being read or written. They allow us to access data as it is being read from disk/network/other I/O.

Streams return smaller parts of the data (using a Buffer), and trigger a callback when new data is available for processing.

Streams are EventEmitters. If our 1 GB file would, for example, need to be processed in some way once, we could use a stream and process the data as soon as it is read. This is useful, since we do not need to hold all of the data in memory in some buffer: after processing, we no longer need to keep the data in memory for this kind of application.

The Node stream interface consists of two parts: Readable streams and Writable streams. Some streams are both readable and writable.



Related Topics



Leave a reply



Submit