Reading txt file contents and storing in array - java

I have been trying to read a txt file. The txt file contains lines e.g
First Line
Second Line
Third Line
.
.
.
Now I am using following code
InputStream is = null;
try {
is = getResources().getAssets().open("myFile.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<String> arrayOfLines = new ArrayList<String>();
Reader reader;
//char[] buffer = new char[2048];
try {
Reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read()) != -1) {
}
}catch (Exception e) {
e.printStackTrace();
}
My question is, how can i store each line in the arrayList. Ofc We have to use a check for "/n" but how.

You could alternatively use the Scanner class.
Scanner in = new Scanner(new File("/path/to/file.txt"));
while(in.hasNextLine()) {
arrayOfLines.add(in.nextLine());
}
You don't have to worry about \n, since Scanner.nextLine() will skip the newline.

This code should work.
ArrayList<String> arrayOfLines = new ArrayList<String>();
FileInputStream fstream = new FileInputStream("myfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
arrayOfLines.add(strLine);
}

This:
int n;
while ((n = reader.read()) != -1) {
}
Should probably look more like this:
String line = reader.readLine();
while (line!=null) {
arrayOfLines.add(line);
line = reader.readLine();
}
Since you are using a BufferedReader, you should be calling readLine() instead of reading into a char buffer. The Reader declaration also needs to be BufferedReader.

Related

How can I ignore a blank line in a srt file using Java

I have a srt file like below and I want to remove blank line : in line no 3
**
1
Line1: 00:00:55,888 --> 00:00:57,875.
Line2:Antarctica
Line3:
Line4:2
Line5:00:00:58,375 --> 00:01:01,512
Line6:An inhospitable wasteland.
**
FileInputStream fin = new FileInputStream("line.srt");
FileOutputStream fout = new FileOutputStream("m/line.srt");
int i = 0;
while(((i =fin.read()) != -1)){
if(i != 0)
fout.write((byte)i);
}
There you go. Steps:
1) FileInputStream fin = new FileInputStream("line.srt"); this is to get the file to a bufferedreader in the next step
2) BufferedReader reader = new BufferedReader(new InputStreamReader(fin)); get the text file to a buffereader
3) PrintWriter out = new PrintWriter("newline.srt"); use a print writer to write the string of every line in the new text file
4) String line = reader.readLine(); read next line
5) while(line != null){
if (!line.trim().equals("")) { check that line is not null and that line is not empty
6) out.println(line); write line (not empty) to the output .srt file
7) line = reader.readLine(); get new line
8) out.close(); close PrintWriter in the end...
import java.io.*;
class RemoveBlankLine {
public static void main(String[] args) throws FileNotFoundException, IOException{
FileInputStream fin = new FileInputStream("line.srt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
PrintWriter out = new PrintWriter("newline.srt");
int i = 0;
String line = reader.readLine();
while(line != null){
if (!line.trim().equals("")) {
out.println(line);
}
line = reader.readLine();
}
out.close();
}
}
INPUT:
**
1
00:00:55,888 --> 00:00:57,875.
Antarctica
2
00:00:58,375 --> 00:01:01,512
An inhospitable wasteland.
**
OUTPUT:
**
1
00:00:55,888 --> 00:00:57,875.
Antarctica
2
00:00:58,375 --> 00:01:01,512
An inhospitable wasteland.
**
By the way, make sure you are clear when you ask your questions, because the way you state your problem I assumed Line1, Line2, etc are part of your input file, and I have prepared another solution which I had to change... Make sure you are clear and precise so that you get the proper answers !
You can try something like :
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("line.srt"));
bw = new BufferedWriter(new FileWriter("m/line.srt"));
for(String line; (line = br.readLine()) != null; ) {
if(line.trim().length() == 0) {
continue;
} else {
bw.write(line);
bw.newLine();
}
}
bw.flush();
bw.close();
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
hope this help
public static void main(String[] args) throws FileNotFoundException, IOException {
Path myPath = Paths.get("e:\\", "1.txt");
List<String> ls ;
ls = Files.readAllLines(myPath, StandardCharsets.US_ASCII);
PrintWriter out = new PrintWriter("e:\\2.txt");
for (int i = 0; i < ls.size(); i++) {
String []temp = ls.get(i).split(":");
if(temp.length>1) {
out.println(ls.get(i));
}
}
out.close();
}

Read text file line by line and store in a class?

I need some help with reading line by line from a file then put it into a class.
My idea is like this: I've saved everything in a text file, it's about 500 lines but this can change that's why I wan't the line number reader and then lnr/5 to get how many times I'll need to run the for loop. I wan't it to first take line 1,2,3,4,5 into a object, then 6,7,8,9,10 and so on. So basically I need each 5 lines go in seperatley.
Code:
public static void g_txt() {
LineNumberReader lnr;
String[] text_array = new String[500];
int nu = 0;
try {
lnr = new LineNumberReader(new FileReader(new File("test.txt")));
lnr.skip(Long.MAX_VALUE);
//System.out.println(lnr.getLineNumber());
lnr.close();
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
text_array[nu] = line;
nu++;
}
} catch (IOException e) {
}
}
as you can see, I now has it in an array. Now I need it to make so 1,2,3,4,5 and so on go in to this:
filmer[antalfilmer] = new FilmSvDe(line1);
filmer[antalfilmer].s_filmbolag(line2);
filmer[antalfilmer].s_producent(line3);
filmer[antalfilmer].s_tid(line4);
filmer[antalfilmer].s_betyg(line5);
filmer[antalfilmer].s_titel(line1);
then antalfilmer++.
public static void g_txt() {
String[] text_array = new String[5];
int nu = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
text_array[nu] = line;
nu++;
if (nu == 5) {
nu = 0;
makeObject(text_array);
}
}
} catch (IOException e) {
}
}
private static void makeObject(String[] text_array) {
// do your object creation here
System.out.println("_________________________________________________");
for (String string : text_array) {
System.out.println(string);
}
System.out.println("_________________________________________________");
}
Try this.

Java - File being read returns null

Hi I am loading a file into my program and assigning each value (stored on a new line to a array) I cant seem to spot why the array holding the file content is null in each index.
private void readAndProcessWords() {
try {
FileReader _fr = new FileReader(FILEPATH);
BufferedReader textReader = new BufferedReader(_fr);
int numLines = getNumLines(textReader);
String[] words = new String[numLines];
for(int i=0;i<numLines;i++){
words[i] = textReader.readLine();
System.out.println(words[i]);
}
//clears memory reserved for this buffered reader
textReader.close();
} catch(IOException e) {
System.out.println(e);
}
}
private int getNumLines(BufferedReader textReader) throws IOException{
String line;
int numLines =0;
while((line = textReader.readLine()) != null){
numLines++;
}
return numLines;
}
}
Solution: add the below code above the loop to 'reset' the file reader
_fr = new FileReader(FILEPATH);
textReader = new BufferedReader(_fr);
The easiest solution is to recreate your Reader, the issue is that calling getNumLines() moves the position in your BufferedReader to the end of file.
BufferedReader textReader = new BufferedReader(_fr);
int numLines = getNumLines(textReader); // <-- textReader is at EOF after this.
textReader.close();
textReader = new BufferedReader(_fr);
Instead of reading your file twice to get the line count (which is slow, annoying, and will not work if the file changes between the two calls), read the lines into a variable-sized list:
private void readAndProcessWords() {
try {
FileReader _fr = new FileReader(FILEPATH);
BufferedReader textReader = new BufferedReader(_fr);
List<String> words = new ArrayList<>();
String line;
while ((line = textReader.readLine()) != null) {
words.add(line);
}
textReader.close();
for (String word : words) {
System.out.println(word);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Good news: this functionality already exists, so you don't need to rewrite it.
private void readAndProcessWords() {
try {
List<String> words = Files.readAllLines(Paths.get(FILEPATH));
for (String word : words) {
System.out.println(word);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Since a buffered reader is an object you pass it as a reference to the getNumLines() not as a copy, so you end up getting a null when you .readLine() on the same buffered reader you sent to the getNumLines() because you have already run .readLine() to its limit.
After running getNumLines() close and reopen the document with a new buffered reader.
I also remember there being a Mark() and Recall() method for buffered reader in java that could also serve as a work around.
I think like.
FileReader _fr = new FileReader(FILEPATH);
BufferedReader textReader = new BufferedReader(_fr);
textReader.Mark();
int numLines = getNumLines(textReader);
textReader.Recall();
String[] words = new String[numLines];
for(int i=0;i<numLines;i++)
{
words[i] = textReader.readLine();
System.out.println(words[i]);
}
//clears memory reserved for this buffered reader
textReader.close();

BufferedReader to skip first line

I am using the following bufferedreader to read the lines of a file,
BufferedReader reader = new BufferedReader(new FileReader(somepath));
while ((line1 = reader.readLine()) != null)
{
//some code
}
Now, I want to skip reading the first line of the file and I don't want to use a counter line int lineno to keep a count of the lines.
How to do this?
You can try this
BufferedReader reader = new BufferedReader(new FileReader(somepath));
reader.readLine(); // this will read the first line
String line1=null;
while ((line1 = reader.readLine()) != null){ //loop will run from 2nd line
//some code
}
You can use the Stream skip() function, like this:
BufferedReader reader = new BufferedReader(new FileReader(somepath));
Stream<String> lines = reader.lines().skip(1);
lines.forEachOrdered(line -> {
...
});
File file = new File("path to file");
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
int count = 0;
while((line = br.readLine()) != null) { // read through file line by line
if(count != 0) { // count == 0 means the first line
System.out.println("That's not the first line");
}
count++; // count increments as you read lines
}
br.close(); // do not forget to close the resources
Use a linenumberreader instead.
LineNumberReader reader = new LineNumberReader(new InputStreamReader(file.getInputStream()));
String line1;
while ((line1 = reader.readLine()) != null)
{
if(reader.getLineNumber()==1){
continue;
}
System.out.println(line1);
}
You can create a counter that contains the value of the starting line:
private final static START_LINE = 1;
BufferedReader reader = new BufferedReader(new FileReader(somepath));
int counter=START_LINE;
while ((line1 = reader.readLine()) != null) {
if(counter>START_LINE){
//your code here
}
counter++;
}
You can do it like this:
BufferedReader buf = new BufferedReader(new FileReader(fileName));
String line = null;
String[] wordsArray;
boolean skipFirstLine = true;
while(true){
line = buf.readLine();
if ( skipFirstLine){ // skip data header
skipFirstLine = false; continue;
}
if(line == null){
break;
}else{
wordsArray = line.split("\t");
}
buf.close();

Best way to read data from a file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to read a text file
In Java I can open a text file like this:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
My question is, how do you read from the following file? The first line is a number (830) representing number of words, and the following lines contain the words.
830
cooking
English
weather
.
.
I want to read the words into a string array. But how do I read the data first?
You're on the right track; I would treat the first line as a special case by parsing it as an integer (see Integer#parseInt(String)) then reading the words as individual lines:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String numLinesStr = reader.readLine();
if (numLinesStr == null) throw new Exception("invalid file format");
List<String> lines = new ArrayList<String>();
int numLines = Integer.parseInt(numLinesStr);
for (int i=0; i<numLines; i++) {
lines.add(reader.readLine());
}
Unless you have some special reason, it's not necessary to keep track of how many lines the file contain. Just use something like this:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
// ...
}
If you're working with Java version greater than 1.5, you can also use the Scanner class:
Scanner sc = new Scanner(new File("someTextFile.txt"));
List<String> words = new ArrayList<String>();
int lines = sc.nextInt();
for(int i = 1; i <= lines; i++) {
words.add(sc.nextLine());
}
String[] w = words.toArray(new String[]{});
Try the class java.io.BufferedReader, created on a java.io.FileReader.
This object has the method readLine, which will read the next line from the file:
try
{
java.io.BufferedReader in =
new java.io.BufferedReader(new java.io.FileReader("filename.txt"));
String str;
while((str = in.readLine()) != null)
{
...
}
}
catch(java.io.IOException ex)
{
}
You could use reflection and do this dynamically:
public static void read() {
try {
BufferedReader reader = new BufferedReader(new FileReader(
"filename.txt"));
String line = reader.readLine();
while (line != null) {
if (Integer.class.isAssignableFrom(line.getClass())) {
int number = Integer.parseInt(line);
System.out.println(number);
} else {
String word = line;
System.out.println(word);
}
line = reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Categories

Resources