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();
Related
I want to read csv file with BufferedReader and split with StringTokenizer. However there is one line in file which contains this line :
ide,12,office,,3208.83,0.18,577.5,4876
Also here is my read method;
public void readFromCSV(){
try {
File file = new File(myFile);
br = new BufferedReader(new FileReader(file));
String line = null;
while((line = br.readLine()) != null) {
st1 = new StringTokenizer(line,"\n");
while(st1.hasMoreTokens()) {
oneLineList = new ArrayList<>();
st2 = new StringTokenizer(st1.nextToken(),",");
for(int i = 0; i < 8; i++) {
oneLineList.add(st2.nextToken());
}
dataList.add(counter,oneLineList);
}
counter++;
}
br.close();
}catch(IOException ex) {
ex.printStackTrace();
}
}
In for statement, there are 8 fields in each line, and dataList is a two-dimensional array list.
I cannot read whole data because of one line contain consecutive coma, how should I do for fix this?
I have a text file with the following format:
String1
String1String2
String1String2String3
....
String1Strin2String3.....String(i)...String(n)
I want to remove some parts of this file to have the following format(result file):
String1
String2
String3
...
String(i)
String(n)
I tried with this fonction but my output file is always empty:
public static void FileFormatted(String inputFile,String outputFile)
{
String FileContent = readFile(inputFile,
StandardCharsets.UTF_8);
String[] FileSentences = FileContent.split("[\n]");
for (int i = 0; i < FileSentences.length; i++)
{
StringBuilder builder = new StringBuilder();
for(int j=1;j<FileSentences.length;j++)
{
int index= FileSentences[j].indexOf("FileSentences[i]");
String temp=FileSentences[j].substring(index);
FileSentences[j]=FileSentences[j].replaceAll(temp," ");
builder.append(FileSentences[j]+ "\n");
}
writeIntoFile(builder, outputFile, true);
}
}
public static void writeIntoFile(StringBuilder stringBuilder,
String txtFilePath, boolean append) {
File file = new File(txtFilePath);
// if file doesn't exists, then create it
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter fw;
try {
fw = new FileWriter(file.getAbsoluteFile(), append);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(stringBuilder.toString());
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Can someone please help me.
Okay, first of all reading the whole file in, in one go is bad practice. Imagine you have a 6gb file, that means you need 6gb of RAM to store that file when you read it in. It would be better to read the file line by line.
So the Aim of the logic would be read line by line.
When we read the first line we can get the length of it.
When we read read the second line we know the length of the first line so that means it is our starting point on the second line. This means you can use sub-string method, passing the start position and end position.
And repeat this logic for line 3,4,...n
The benefit of this is that you don't waste memory, you are only storing the size of the line in text.
Update
I have written the code that I suggested earlier. It's pretty basic and there is no validation so you will need to add to it. But it covers the basics
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fileReader);
int startPosition = 0;
String line;
ArrayList<String> items = new ArrayList<String>();
while((line = br.readLine() ) != null)
{
items.add(line.substring(startPosition, line.length()));
System.out.println(line.substring(startPosition, line.length()));
startPosition = line.length();
}
write("test2.txt", items);
}
public static void write (String filename, ArrayList<String> items) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
for (String item : items) {
outputWriter.write(item);
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}
be sure the pattern is consistent in the hole file, then Do this:
public static void main(String[] args) {
String wordTofind = "String";
String st = "String1String2String3String4";
String[] arra = st.split(wordTofind);
for (int i = 1; i < arra.length - 1; i++) {
System.out.println(wordTofind + arra[i]);
//write to a file or similar.
}
}
you can use regex too, but this is acceptable...
I am new to Java and it has all been self-taught. I enjoy working with the code and it is just a hobby, so, I don't have any formal education on the topic.
I am at the point now where I am learning to read from a text file. The code that I have been given isn't correct. It works when I hardcode the exact number of lines but if I use a "for" loop to sense how many lines, it doesn't work.
I have altered it a bit from what I was given. Here is where I am now:
This is my main class
package textfiles;
import java.io.IOException;
public class FileData {
public static void main(String[] args) throws IOException {
String file_name = "C:/Users/Desktop/test.txt";
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int nLines = file.readLines();
int i = 0;
for (i = 0; i < nLines; i++) {
System.out.println(aryLines[i]);
}
}
}
This is my class that will read the text file and sense the number of lines
package textfiles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
int numberOfLines = 0;
String aLine;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
int i;
for (i = 0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
}
Please, keep in mind that I am self-taught; I may not indent correctly or I may make simple mistakes but don't be rude. Can someone look this over and see why it is not sensing the number of lines (int numberOfLines) and why it won't work unless I hardcode the number of lines in the readLines() method.
The problem is, you set the number of lines to read as zero with int numberOfLines = 0;
I'd rather suggest to use a list for the lines, and then convert it to an array.
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
//int numberOfLines = 0; //this is not needed
List<String> textData = new ArrayList<String>(); //we don't know how many lines are there going to be in the file
//this part should work akin to the readLines part
String aLine;
while ((aLine = bf.readLine()) != null) {
textData.add(aLine); //add the line to the list
}
textReader.close();
return textData.toArray(new String[textData.size()]); //convert it to an array, and return
}
}
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
textData is an empty array. The following for loop wont do anything.
Note also that this is not the best way to read a file line by line. Here is a proper example on how to get the lines from a text file:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
I also suggest that you read tutorials on object oriented concepts.
This is a class that I wrote awhile back that I think you may find helpful.
public class FileIO {
static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while ((line = input.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
} finally {
input.close();
}
} catch (IOException ex) {
}
return contents.toString();
}
static public File OpenFile()
{
return (FileIO.FileDialog("Open"));
}
static private File FileDialog(String buttonText)
{
String defaultDirectory = System.getProperty("user.dir");
final JFileChooser jfc = new JFileChooser(defaultDirectory);
jfc.setMultiSelectionEnabled(false);
jfc.setApproveButtonText(buttonText);
if (jfc.showOpenDialog(jfc) != JFileChooser.APPROVE_OPTION)
{
return (null);
}
File file = jfc.getSelectedFile();
return (file);
}
}
It is used:
File file = FileIO.OpenFile();
It is designed specifically for reading in files and nothing else, so can hopefully be a useful example to look at in your learning.
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.
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();
}
}