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) {}
}
}
Related
The code should do a reverse and output the result to out.txt, but this does not happen, can you explain my mistake in the code. Thanks in advance
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileReader input = new FileReader("in.txt");
FileWriter output = new FileWriter("out.txt");
BufferedReader sb = new BufferedReader(input);
String data;
while ((data = sb.readLine()) != null) {
String[] words = data.split(" ");
for (String a : words) {
StringBuilder builder = new StringBuilder(a);
builder.reverse();
while ((sb.read()) != -1) {
output.write(String.valueOf(builder.reverse()));
}
}
}
}
}
You are trying to reverse the string twice because of that the string is getting back to the original string. Also, there is an unnecessary (as per my understanding) while loop inside the for loop (I have removed that in my answer).
Try the below code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileReader input = new FileReader("in.txt");
FileWriter output = new FileWriter("out.txt");
BufferedReader sb = new BufferedReader(input);
String data;
while ((data = sb.readLine()) != null) {
String[] words = data.split(" ");
// above statement can be replaced with
// String[] words = data.split(" {34}");
for (String a : words) {
StringBuilder builder = new StringBuilder(a);
// why while loop is required?
//while ((sb.read()) != -1) {
output.write(builder.reverse().toString());
output.flush(); // flush data to the file
//}
}
}
output.close();
}
}
Read about File writer here on how to flush data and also close the writer after writing is completed.
I have tried out.append(s); However my problems grow out of control. Anyone else see anything my eyes are missing?
public void writeToFile()
{
PrintWriter out = null;
try
{
out = new PrintWriter(new BufferedWriter(new FileWriter("course.txt", true)));
for (String courseName:courseData.keySet())
{
Course course = courseData.get(courseName);
if (!course.isEmpty())
{
ArrayList<String> students = course.getStudentList();
for (String s : students)
{
out.println(courseName + "<<<<" + s);
}
}
else
{
out.println(courseName + "<<<<");
}
}
} catch (IOException ex)
{
Logger.getLogger(CourseApp.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
out.close();
}
}
My text file should look like this after I make an entry.
However this is the result I actually get.
//use pw.flush() at the end to avoid multiple copies
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.FileHandler;
public class MergeFiles {
public static void main(String[] arg) throws IOException
{
File dir=new File("E:\\videos\\assignments\\fileWork");
File file = new File("E:\\videos\\assignments\\fileWork\\MergeAllAssignments.txt");
file.getParentFile().mkdirs();
PrintWriter pw=new PrintWriter(file);
String[] fileNames=dir.list();
for(String files:fileNames)
{
System.out.println("Reading file "+files);
File f=new File(dir,files);//instance of file to read
BufferedReader br=new BufferedReader(new FileReader(f));//f>>filereader>>bufferedReader
String line=br.readLine();//reading line by line
while(line!=null)
{
System.out.println(line);
pw.println(line);
line=br.readLine();
}
pw.println("\r\n\n\r\n next days assignment>>>>>>>>>>>>>>>>>>>\r\n\r\n\r\n\r\n\r\n");
//to write everything in pw object to destinatio
}
pw.flush();
pw.close();
System.out.println("Copying completed");
}
}
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'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];