Reading a Simple Text File

Reading a plain text file in Java

ASCII is a TEXT file so you would use Readers for reading. Java also supports reading from a binary file using InputStreams. If the files being read are huge then you would want to use a BufferedReader on top of a FileReader to improve read performance.

Go through this article on how to use a Reader

I'd also recommend you download and read this wonderful (yet free) book called Thinking In Java

In Java 7:

new String(Files.readAllBytes(...))

(docs)
or

Files.readAllLines(...)

(docs)

In Java 8:

Files.lines(..).forEach(...)

(docs)

Reading from a plain text file

Reading them into a list is trivially done with readlines():

f = open('your-file.dat')
yourList = f.readlines()

If you need the newlines stripped out you can use ars' method, or do:

yourList = [line.rstrip('\n') for line in f]

If you want a dictionary with keys from 1 to the length of the list, the first way that comes to mind is to make the list as above and then do:

yourDict = dict(zip(xrange(1, len(yourList)+1), yourList))

Reading a plain text file

You can reach a file from context in android.

Context Context;
AssetManager mngr = context.getAssets();
String line;
try {

BufferedReader br = new BufferedReader(new FileReader(mngr.open("words.txt")));
if (!br.ready()) {
throw new IOException();
}
while ((line = br.readLine()) != null) {
words.add(line);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}

Or try this:

String line;
try {

BufferedReader br = new BufferedReader(new FileReader(getApplicationContext().getAssets().open("words.txt")));
if (!br.ready()) {
throw new IOException();
}
while ((line = br.readLine()) != null) {
words.add(line);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}

Python reading from txt file

There are a lot of answers with poor practices here. The best way is to realise that you can iterate on file objects directly

path_to_file = r"D:\(my user name)\Documents\names.txt"
with open(path_to_file) as file_object: # this is a safe way of opening files
for line in file_object:
print(line)

Or if you want to save that as a list and access by index names[0] use:

with open(path_to_file) as file_object:  # this is a safe way of opening files
names = [line.rstrip('\n') for line in file_object] # remove \n at end

print(names[0]) # --> name 1
print(names[1]) # --> name 2

A quick explanation about the with. Don't do

file = open(path)
# do stuff

because you risk corrupting your data. You must close your file. However

file = open(path)
# do stuff
file.close()

is also dangerous since #do stuff may fail, in which case the file will never be closed. One way is to use

try:
file = open(path)
# do stuff
finally:
file.close()

where no matter what happens in # do stuff, the file.close() will always be executed. Still, this is a bit verbose, and a quicker way to write this for file objects is

with open(path) as file:
# do stuff

Reading a simple text file

Place your text file in the /assets directory under the Android project. Use AssetManager class to access it.

AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");

Or you can also put the file in the /res/raw directory, where the file will be indexed and is accessible by an id in the R file:

InputStream is = context.getResources().openRawResource(R.raw.test);

Reading a plain text file with multiple flags java

I would avoid using scanner delimiters. Just read each line and process it in code. For each line, first throw away (or ignore) any leading white space. Then if the line starts with a delimiter, wrap up any pending link/output (see below for what that means). Then,

  • if the line starts with -~-, the text from there to the end of the line is the start of a link, so start accumulating link text (in, say a StringBuilder). Also, if you have a non-empty output list, append the list to the list of lists output.
  • if it starts with -@-, it's the start of an output, so start accumulating output text.
  • if it starts with neither delimiter, it's a continuation line, so append the rest of the line to the current link/output accumulator (perhaps after appending a space or newline).

To "wrap up any pending link/output", convert the current contents of the StringBuilder to a String and add to the appropriate list. Also append any non-empty output list to output.

There are a lot of bookkeeping details to attend to here that I haven't addressed, but that's the basic idea.

In C, how should I read a text file and print all strings

The simplest way is to read a character, and print it right after reading:

int c;
FILE *file;
file = fopen("test.txt", "r");
if (file) {
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
}

c is int above, since EOF is a negative number, and a plain char may be unsigned.

If you want to read the file in chunks, but without dynamic memory allocation, you can do:

#define CHUNK 1024 /* read 1024 bytes at a time */
char buf[CHUNK];
FILE *file;
size_t nread;

file = fopen("test.txt", "r");
if (file) {
while ((nread = fread(buf, 1, sizeof buf, file)) > 0)
fwrite(buf, 1, nread, stdout);
if (ferror(file)) {
/* deal with error */
}
fclose(file);
}

The second method above is essentially how you will read a file with a dynamically allocated array:

char *buf = malloc(chunk);

if (buf == NULL) {
/* deal with malloc() failure */
}

/* otherwise do this. Note 'chunk' instead of 'sizeof buf' */
while ((nread = fread(buf, 1, chunk, file)) > 0) {
/* as above */
}

Your method of fscanf() with %s as format loses information about whitespace in the file, so it is not exactly copying a file to stdout.



Related Topics



Leave a reply



Submit