I'm trying to read a file in java. In that file, some string is given which I want to print. But my code prints only lines of even numbers and skips lines of odd numbers.
I searched for that in stackoverflow, but have found no solution previously answered.
My code is given below...
//main class
import java.io.IOException;
public class takingInputFrpmFile {
public static void main(String[] args) throws IOException {
String filePath = "F:/Path/in.txt";
try
{
readFile rF = new readFile(filePath);
String[] receivedArray = rF.Read();
for(int i=0;i<receivedArray.length;i++)
System.out.println(receivedArray[i]);
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
// class called from main class
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class readFile {
private String path;
public readFile(String path)
{
this.path=path;
}
public String[] Read() throws IOException
{
FileReader fR = new FileReader(path);
BufferedReader bR = new BufferedReader(fR);
String[] textData = new String[110];
String check;
int i=0;
while((check = bR.readLine()) != null)
{
textData[i] = bR.readLine();
i++;
}
bR.close();
return textData;
}
}
The file contains this lines...
This is the output of my code....
What is wrong with my code? What should I change? How to get rid of printing that last nulls ? Help please... Thanks in advance...
You are first reading the line and checking it's not null, then you read another line.
while((check = bR.readLine()) != null)
{
textData[i] = check; //Changed this to check
i++;
}
That one will work.
You are currently declaring String array which has size of 110. Is your file really 110 line long? You probably should use list instead.
public List<String> Read() throws IOException
{
FileReader fR = new FileReader(path);
BufferedReader bR = new BufferedReader(fR);
List<String> textData = new ArrayList<>();
String check;
while((check = bR.readLine()) != null)
{
textData.add(check);
}
bR.close();
return textData;
}
If you really want to return string array you can use:
return textData.toArray(new String[textData.size()]);
You are reading file lines twice, one when you do
check = bR.readLine()
and other when you do
textData[i] = bR.readLine();
(Each bR.readLine() reads one line)
Try changing your loop for something like
while ((textData[i] = bR.readLine()) != null) {
i++;
}
To get rid of the nulls, you can use a List instead of using a fixed size (110) array.
I suggest the following code:
//main class
import java.io.IOException;
import java.util.List;
public class Prueba {
public static void main(String[] args) throws IOException {
String filePath = "E:/Temp/in.txt";
try {
ReadFile rF = new ReadFile(filePath);
List<String> receivedArray = rF.read();
for (String currentLine : receivedArray) {
System.out.println(currentLine);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
//class called from main class
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadFile {
private final String path;
public ReadFile(String path) {
this.path = path;
}
public List<String> read() throws IOException {
// Create an empty List to protect against NPE
List<String> textData = new ArrayList<String>();
FileReader fR = null;
BufferedReader bR = null;
try {
fR = new FileReader(path);
bR = new BufferedReader(fR);
String line;
while ((line = bR.readLine()) != null) {
textData.add(line);
}
} catch (IOException e) {
throw e;
} finally {
// Close all the open resources
bR.close();
fR.close();
}
return textData;
}
}
Anyway, as Mukit Chowdhury suggested, please respect code conventions to make your code more readable (you can Google "Java code conventions" or use a well stablished ones)
It seems you do 2 read statements. Try something like:
while((check = bR.readLine()) != null)
{
textData[i] = check;
i++;
}
your line pointer incrementing two times,
while((check = bR.readLine()) != null){
textData[i] = bR.readLine();
i++;
}
Replace bR.readLine() to check in your while loop.
while((check = bR.readLine()) != null){
textData[i] = check ;
i++;
}
You call readline twice. Your loop should read
for(; (check = br.readline()) != null; textdata[i++] = check);
Or something to that effect
In Java 8, reading all lines from a File into a List<String> is easily done using utility classes from the java.nio.file package:
try {
List<String> lines = Files.readAllLines(Paths.get("/path/to/file"));
} catch (IOException e) {
// handle error
}
It's really no longer necessary to use external libraries or to re-invent the wheel for such a common task :)
From your code sample
here
while((check = bR.readLine()) != null) {
textData[i] = bR.readLine();
i++;
}
replace it with
while((check = bR.readLine()) != null) {
textData[i] = check ;
i++;
}
Related
I have successfully added Csv reading functionality to my application. The setup that work is I have a base class called CSVReader. For each csv file, I create A new Class and it extends from CSVReader. The setup I am currently working on is to have only one class that can be used for any csv file. SO far my code seems to make sense, but clearly is not working therefore I need to fix something.
Here is the base CSVReader
package com.kbs.utilities.csvReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class CSVReader {
public ArrayList<String[]> readCsvFile(String filePath, boolean headerExists) { //Transfers info from CsvFile to an arraylist of string arrays
String line = "";
BufferedReader br = null;
ArrayList<String[]> arrayClone = new ArrayList<String[]>(); //Container to store contents of String array
try {
FileReader fileReader = new FileReader(filePath); //creates file reader object in the specified csv FIle
br = new BufferedReader(fileReader);
if(headerExists) { //if CSVFile has header then read the first line and put it into a variable
String headerLine = br.readLine();
headerLine.chars(); //pointless line of code, just here to remove the warning of unused variable
}
while((line = br.readLine())!= null) {
String[] currentRow = line.split(",");
arrayClone.add(currentRow);
}
} catch (FileNotFoundException e) {
// Error handling statement for throwing exception in case File isn't found
e.printStackTrace();
} catch(IOException e) {
//// Error handling statement for throwing exception in case File can't be accessed using BufferedReader object
e.printStackTrace();
}
finally {
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return arrayClone;
}
}
This is the Class that extends CSVReader and is used to initiate the data from the specified csv
public class InitializeCSV extends CSVReader{
public ArrayList<Object> initCSV() {
String csvFile = "C:\\Users\\kamalu\\Desktop\\Developer\\misc\\sandbox\\kbs-petshop\\trunk\\WebContent\\WEB-INF\\data\\"+csvFileName+".csv";
boolean header = true;
ArrayList<String[]> csvStringArray = readCsvFile(csvFile, header); /
ArrayList<Object> list = new ArrayList<Object>();
for(String[] iteration : csvStringArray) {
Object[] iterationCopy = (Object[]) new Object();//Initializing using the array[] constructor
list.add(iterationCopy);
}
return list;
}
}
Suppose that file.txt only contains "Hello". When I compile the Java code, it shows
Error: This method must return a result of type java.lang.String in line5.
When I print in readTxt function, that works, it can show "Hello".
I already check the result is correctly String type, but it also shows compiler error. How can I make the return value to the main function?
import java.io.*;
import java.lang.String;
public class ReadTxtFile {
public static String readTxt(String filePath) {
try {
File file = new File(filePath);
if(file.isFile() && file.exists()) {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(isr);
String lineTxt = null;
lineTxt = br.readLine();
//System.out.println(lineTxt);
br.close();
return lineTxt;
} else {
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
String filePath = "C:/file.txt";
String fileword = readTxt(filePath);
System.out.println(fileword);
}
}
You promised to return a String from your method, so you now have to do that. The only way around that promise is to throw an exception.
public static String readTxt(String filePath) { // Here you promise to return a String
try {
...
if(file.isFile() && file.exists()) {
...
return lineTxt; // Here you return a String as promised
} else {
// Here you're missing either return or throw
}
} catch (Exception e) {
// Here you're missing either return or throw
}
}
This is fundamentally a design problem - what should your method do if it fails to read the file for some reason? Return a special string like "Error"? Return null? Fail and throw and exception? Something else?
Answer that to yourself and it will be clear to you how to fix the code.
There are several best practices you should follow that will prevent future error. I have tried to cover them. Not saying mine is the perfect one, but you will get the idea.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class StackOverFlow {
public static void main(String[] args) {
try {
String sText = getFileText("C:/file.txt");
System.out.println("Text is: " + sText);
} catch (FileNotFoundException e) {
System.out.println("File not Found");
} catch (IOException e) {
System.out.println("#Error while reading text: " + e.getMessage());
}
}
private static String getFileText(String filePath) throws FileNotFoundException, IOException {
File file = new File(filePath);
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
}finally {
reader.close();
}
return new String(stringBuilder);
}
}
Here is my code
package sequentialFilePractice;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ReadFile{
static String line = "";
ReadFile() throws FileNotFoundException{
readTheFile();
CSVtoArrayList();
}
public String readTheFile() throws FileNotFoundException{
String csvFile = "H:\\S6\\AH Computing\\Java Practice\\test.csv";
BufferedReader br = null;
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return line;
}
public static ArrayList<String> CSVtoArrayList() {
ArrayList<String> splitCSV = new ArrayList<>();
if (line != null) {
String[] splitData = line.split("\\s*,\\s*");
for (int i = 0; i < splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
splitCSV.add(splitData[i].trim());
}
}
}
for(int j = 0;j < splitCSV.size();j++){
System.out.println(splitCSV.get(j));
}
return splitCSV;
}
public static void main(String[]args) throws IOException{
ReadFile f = new ReadFile();
}
}
The code compiles and the file exists. I can print line and it prints the contents of the file however when I print the arrayList, nothing is output so it has not been copied. This is my first use of sequential files in java.
Do you HAVE to read the file manually? If not, you should check out http://opencsv.sourceforge.net/, it allows you to read a CSV directly into a List<String[]> instead of having to deal with the admin of looping, splitting the line and creating a list.
In essence reducing your code to:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List myEntries = reader.readAll();
I am trying to use following code to edit html page using java.
package com.XXX.xxx.xxx
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class HTMLReading {
/**
* #param args
*/
public static void main(String[] args) {
StringBuilder contentBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new FileReader("C:\\ItemDetails.html"));
String str;
while ((str = in.readLine()) != null) {
if(str.equals("<div id=\"row2\" style=\"display:none;\" ><ul>")) {
// add following lines to html
//<li><b>Comments</b></li><ul><li>Testing for comment</li></ul>
}
System.out.println(str);
}
in.close();
} catch (IOException e) {
}
}
}
On reading perticular line, I want to insert some new line to html.
//<li><b>Comments</b></li><ul><li>Testing for comment</li></ul>
I tried Append, but it adds the line at end, not at the place where I want.
And my requirement is I have to use only JAVA only for this.
Any thoughts!
You can use Java.io.BufferedWriter.newLine() method.
It's non static method, you can find some documantation here:
http://www.tutorialspoint.com/java/io/bufferedwriter_newline.htm
Also,
You better use StringBuffer and not just String, because it's an immutable object like:
StringBuffer sb = new StringBuffer();
sb.append ("<br>blabla<br>");
You could try something like this:
String str;
StringBuilder contentBuilder = new StringBuilder();
while ((str = in.readLine()) != null) {
if(str.equals("<div id=\"row2\" style=\"display:none;\" ><ul>")) {
contentBuilder.append("add your content" + str);
}
else
{
contentBuilder.append(str);
}
System.out.println(str);
}
You can store it in a String then write combined to the file over what was there.
Newlines are represented in Java as "\n". It sounds like you want your StringBuilder to contain the contents of the original file, plus the additional lines you describe. To accomplish that your code might look like:
public static void main(String[] args) {
StringBuilder contentBuilder = new StringBuilder();
try (BufferedReader in = new BufferedReader(new FileReader("C:\\ItemDetails.html"))) {
String str;
while ((str = in.readLine()) != null) {
contentBuilder.append(str);
if (str.equals("<div id=\"row2\" style=\"display:none;\" ><ul>")) {
contentBuilder.append("\n<li><b>Comments</b></li><ul><li>Testing for comment</li></ul>\n);
}
}
} catch (IOException e) {
}
System.out.println(contentBuilder.toString());
}
I need to create a textfile that combines any numbers of textfiles from the same folder. They need to be accessed via the arguments in my main-method, so that it look for the filenames I write. The last file name should be the destination file.
So far my code is creating a new file that has the last string I enter as a name, but it is an empty file. I suspect that my BufferedReader class is not doing what it should, but I'm at a loss. Here is my code. First a driver class and the the actual program. Thanks so much for any help you're able to provide!
public class Driver {
public static void main(String[] args)
{
CatFiles cat = new CatFiles(args);
cat.bookCombiner();
}
}
This is where it goes wrong.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
public class CatFiles {
private String[] files;
public CatFiles(String[] files) {
this.files = files;
}
public String getDest() {
String destination = null;
for (int i = 0; i < files.length; i++) {
destination = files[i];
}
return destination;
}
public void bookCombiner() {
BufferedReader reader = null;
try {
FileWriter writer = new FileWriter(getDest());
for (int i = 0; i < files.length - 1; i++) {
File file = new File(files[i]);
String line = null;
reader = new BufferedReader(new FileReader(file));
if ((line = reader.readLine()) != null) {
writer.write(files.length - 1);
}
}
writer.close();
} catch (Exception e) {
System.out.println(e);
} finally {
try{
reader.close();
} catch(IOException e){
e.printStackTrace();
}
}
}
}
you never use writer to write line. Change:
if ((line = reader.readLine()) != null) {
writer.write(files.length - 1);
}
to
while ((line = reader.readLine()) != null) {
writer.write(line);
}
Couple of issues:
You are using if ((line = reader.readLine()) != null) instead of while which will just write the file length - 1 once into target file.
You are using writer.write(files.length - 1); to write to last file, which should be writer.write(line);
You have probably an error in your getDest() method. Now it just returns last element from files[] array. It is equivalent to:
return files[files.length - 1];