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();
Related
This question already has answers here:
Java Scanner to print previous and next lines
(2 answers)
Closed 6 years ago.
I have a text file from which according to some keywords I have to read that line and write that line into excel file. I did this, now I need to read next line and previous line and that lines also I need to write into excel sheet in different columns. How can I do this.
rahul1.txt
ABCD1 abhishek1 duplicatevalue jgf
ABCD2 abhishek2 duplicatevalue jgf
ABCD3 abhishek3 duplicatevalue jgf
ABCD4 abhishek4 duplicatevalue jgf
while (st1.hasMoreTokens()) {String txt = st1.nextToken();if (txt.contains("abhishek2")) {l1.add(txt);}
How can I print
ABCD1 abhishek1 duplicatevalue jgf prev Line
and
ABCD3 abhishek3 duplicatevalue jgf Next Line
in different column?
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;`
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class ReadWrite {
int rownum = 1;
HSSFSheet firstSheet;
Collection<File> files;
HSSFWorkbook workbook;
File exactFile;
boolean retu;
// BufferedReader reader = null;
{
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("SampleSheet");
Row headerRow = firstSheet.createRow(0);
// headerRow.createCell(0).setCellValue("#");
headerRow.createCell(0).setCellValue("ID");
headerRow.createCell(1).setCellValue(Message");
headerRow.createCell(2).setCellValue("name");
headerRow.createCell(3).setCellValue("address");
headerRow.createCell(4).setCellValue("contact");
headerRow.createCell(5).setCellValue("Next");
headerRow.createCell(6).setCellValue("Prev");
}
public static void main(String args[]) {
ReadWrite class2 = new ReadWrite();
class2.readfile();
}
void readfile() {
try {
FileInputStream fInput = new FileInputStream(
"D:\\Rahul\\rahul1.txt");
DataInputStream dis = new DataInputStream(fInput);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String lineStr;
String prevStr = "";
String nextStr = "";
//List<String> l1 = new ArrayList<String>();
int i;
int seqno = 1;
while ((lineStr = br.readLine()) != null) {
List<String> l1 = new ArrayList<String>();
if (lineStr.contains("Oracle")
|| lineStr.contains("SAP")
|| lineStr.contains("J2EE")) {
l1.add("C1");
l1.add(lineStr);
l1.add("M1");
l1.add("R1");
l1.add("V1");
l1.add(nextStr);
l1.add(prevStr);
} else {
prevStr = lineStr;
}
try {
if (l1 != null && l1.size() > 0)
retu = writenameinsheet(l1);
} catch (Exception e) {
e.printStackTrace();
}
seqno++;
i = 1;
}br.close();
FileOutputStream fos = null;
try {
File excelFile = new File("D:\\Rahul\\rahul.xls");
fos = new FileOutputStream(excelFile);
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
boolean writenameinsheet(List<String> l1) throws Exception {
try {
Row row = firstSheet.createRow(rownum);
for (int j = 0; j < l1.size(); j++){
Cell cell = row.createCell(j);
cell.setCellValue(l1.get(j));
}rownum++;
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return true;
}
}
I have a huge CSV file.I have to read it and store in a database using java.below code only read about 2000 rows from that file and store it into database.why? note the below calculation is to change the seconds to minutes with approximation.dont think a lot about that
import com.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ReadCSV {
public static void main(String[] args) throws SQLException{
MainController mc = new MainController();
boolean status=false;
String csvFile = "C:/Users/Thanushiya/Desktop/mobios/internship/csvfile/csvfile/Master.csv";
CSVReader reader = null;
List myList = new ArrayList();
String[] row = null;
int duration_m = 0;
try {
reader = new CSVReader (new FileReader(csvFile), ',', '\'', 17);
myList = reader.readAll();
int i=0;
for (Object object : myList) {
row = (String[]) object;
float duration_float = Float.parseFloat(row[12]) / 60 ;
float duration_mod = duration_float % 1 ;
if(Integer.parseInt(row[12]) <= 60){
duration_m = 1;
}
else{
if(duration_mod == 0 ){
duration_m = (int) duration_float;
}
else{
duration_m = ((int) duration_float) + 1;
}
}
String query = "INSERT INTO master(msisdn,serv,start,end,ringwithdurartion,duration_s,status,cid,duration_m) values ('"+row[0]+"','"+row[4]+"','"+row[8]+"','"+row[10]+"','"+row[11]+"','"+row[12]+"','"+row[13]+"','"+row[15]+"','"+duration_m+"')";
status=mc.insertData(query);
}//end for
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
With readAll() you're loading (or at least trying to load) the entire file into memory at once. That will severely limit the number of lines you can read before running out of memory. As indicated on the OpenCSV homepage, there's also an iterator that reads line per line:
CSVReader reader = new CSVReader(new FileReader("C:/Users/Thanushiya/Desktop/mobios/internship/csvfile/csvfile/Master.csv"), ',', '\'', 17);
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// put the code from your for loop here
}
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++;
}
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];
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.LineNumberReader;
public class ReadingfromModellerOutput {
public static void main(String args[])throws Exception
{
// BufferedReader br = new BufferedReader(new FileReader("ModellerOutput.txt"));
LineNumberReader reader= new LineNumberReader(new FileReader("ModellerOutput1.txt"));
String line;
while ((line = reader.readLine()) != null)
{
if(line.startsWith("Summary"))
{
System.out.println(reader.getLineNumber());
for(int i=reader.getLineNumber();i<=(reader.getLineNumber()+50);i++)
{
System.out.println(reader.getLineNumber());
writeTofile(line);
}
}
}
}
public static void writeTofile(String line)
{
//System.out.println(reader.getLineNumber());
// for(int i=reader.getLineNumber();i<=(reader.getLineNumber()+50);i++)
// {
// System.out.println(reader.getLineNumber());
try
{
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Output_1.txt"), true));
System.out.println("Hi");
bw.write(line);
bw.newLine();
bw.close();
}
catch (Exception e) {}
}
}
I am trying to write a code to extract 50 lines from a text file following the line which starts with
Summary of the restraint violations:
The above code is writing the same line Summary of the restraint violations: 50 times. Please help.
System.out.println(reader.getLineNumber());
line = reader.readLine(); // You forgot to put this.
writeTofile(line);
Also do not forget to put a break; after your for loop(within the if), so that you don't end up writing more lines post your 50 lines.
line = reader.readLine();
Above line should have been inside the for loop.
I think you should be reading lines inside the for loop.
But you must then check again for end of file. Look at this implementation:
String line = reader.readLine();
while (line != null) {
if (line.startsWith("Summary")) {
for (int i = 0; i < 50; i++) {
line = reader.readLine();
if (line != null) {
writeTofile(line);
} else {
break;
}
}
}
}
Try this program. With proper Break statements
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.LineNumberReader;
public class ReadingfromModellerOutput {
public static void main(String args[])throws Exception
{
// BufferedReader br = new BufferedReader(new FileReader("ModellerOutput.txt"));
LineNumberReader reader= new LineNumberReader(new FileReader("ModellerOutput1.txt"));
String line;
while ((line = reader.readLine()) != null)
{
if(line.startsWith("Summary"))
{
System.out.println(reader.getLineNumber());
for(int i=reader.getLineNumber();i<=(reader.getLineNumber()+50);i++)
{
System.out.println(reader.getLineNumber());
writeTofile(line);
}
break;
}
}
}
public static void writeTofile(String line)
{
//System.out.println(reader.getLineNumber());
// for(int i=reader.getLineNumber();i<=(reader.getLineNumber()+50);i++)
// {
// System.out.println(reader.getLineNumber());
try
{
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Output_1.txt"), true));
System.out.println("Hi");
bw.write(line);
bw.newLine();
bw.close();
}
catch (Exception e) {}
}
}