How can I write all the pages in the text document - java

I am trying to write extracted text of the pdf file into text document but currently, only the first page is being written in the text document although 6 pages are being output in the console of eclipse.
How can I fix that?
I appreciate any help.
try {
PdfReader reader = new PdfReader("D:\\hl_sv\\L09MF.pdf");
int pagenumber = reader.getNumberOfPages();
for (int i = 1; i <= pagenumber; i++) {
System.out.println("==================PAGE NUMBER " + i
+ "===================");
String line = PdfTextExtractor.getTextFromPage(reader, i);
PrintWriter out = new PrintWriter("D:\\hl_sv\\L09MF.txt");
for (String s : line.split("\n")) {
out.println(s);
}
out.close();
System.out.println(line);
}

Try moving the instantiation and closing of the PrintWriter outside of the main for loop:
try {
PdfReader reader = new PdfReader("D:\\hl_sv\\L09MF.pdf");
int pagenumber = reader.getNumberOfPages();
PrintWriter out = new PrintWriter("D:\\hl_sv\\L09MF.txt");
for (int i = 1; i <= pagenumber; i++) {
System.out.println("==================PAGE NUMBER " + i
+ "===================");
String line = PdfTextExtractor.getTextFromPage(reader, i);
for (String s : line.split("\n")) {
out.println(s);
}
System.out.println(line);
}
out.close();
I'm not sure if that'll do the trick but it may help as the PrintWriterkeeps opening and closing every page.

Try to use your output variable out of loop, maybe helps
try {
PdfReader reader = new PdfReader("D:\\hl_sv\\L09MF.pdf");
PrintWriter out = new PrintWriter("D:\\hl_sv\\L09MF.txt");
int pagenumber = reader.getNumberOfPages();
for (int i = 1; i <= pagenumber; i++) {
System.out.println("==================PAGE NUMBER " + i
+ "===================");
String line = PdfTextExtractor.getTextFromPage(reader, i);
for (String s : line.split("\n")) {
out.println(s);
}
System.out.println(line);
}
out.close();

Related

Split lines with "," and do a trim on every element [duplicate]

This is some code that I found to help with reading in a 2D Array, but the problem I am having is this will only work when reading a list of number structured like:
73
56
30
75
80
ect..
What I want is to be able to read multiple lines that are structured like this:
1,0,1,1,0,1,0,1,0,1
1,0,0,1,0,0,0,1,0,1
1,1,0,1,0,1,0,1,1,1
I just want to essentially import each line as an array, while structuring them like an array in the text file.
Everything I have read says to use scan.usedelimiter(","); but everywhere I try to use it the program throws straight to the catch that replies "Error converting number". If anyone can help I would greatly appreciate it. I also saw some information about using split for the buffered reader, but I don't know which would be better to use/why/how.
String filename = "res/test.txt"; // Finds the file you want to test.
try{
FileReader ConnectionToFile = new FileReader(filename);
BufferedReader read = new BufferedReader(ConnectionToFile);
Scanner scan = new Scanner(read);
int[][] Spaces = new int[10][10];
int counter = 0;
try{
while(scan.hasNext() && counter < 10)
{
for(int i = 0; i < 10; i++)
{
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = scan.nextInt();
}
}
}
for(int i = 0; i < 10; i++)
{
//Prints out Arrays to the Console, (not needed in final)
System.out.println("Array" + (i + 1) + " is: " + Spaces[i][0] + ", " + Spaces[i][1] + ", " + Spaces[i][2] + ", " + Spaces[i][3] + ", " + Spaces[i][4] + ", " + Spaces[i][5] + ", " + Spaces[i][6]+ ", " + Spaces[i][7]+ ", " + Spaces[i][8]+ ", " + Spaces[i][9]);
}
}
catch(InputMismatchException e)
{
System.out.println("Error converting number");
}
scan.close();
read.close();
}
catch (IOException e)
{
System.out.println("IO-Error open/close of file" + filename);
}
}
I provide my code here.
public static int[][] readArray(String path) throws IOException {
//1,0,1,1,0,1,0,1,0,1
int[][] result = new int[3][10];
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
Scanner scanner = null;
line = reader.readLine();
if(line == null) {
return result;
}
String pattern = createPattern(line);
int lineNumber = 0;
MatchResult temp = null;
while(line != null) {
scanner = new Scanner(line);
scanner.findInLine(pattern);
temp = scanner.match();
int count = temp.groupCount();
for(int i=1;i<=count;i++) {
result[lineNumber][i-1] = Integer.parseInt(temp.group(i));
}
lineNumber++;
scanner.close();
line = reader.readLine();
}
return result;
}
public static String createPattern(String line) {
char[] chars = line.toCharArray();
StringBuilder pattern = new StringBuilder();;
for(char c : chars) {
if(',' == c) {
pattern.append(',');
} else {
pattern.append("(\\d+)");
}
}
return pattern.toString();
}
The following piece of code snippet might be helpful. The basic idea is to read each line and parse out CSV. Please be advised that CSV parsing is generally hard and mostly requires specialized library (such as CSVReader). However, the issue in hand is relatively straightforward.
try {
String line = "";
int rowNumber = 0;
while(scan.hasNextLine()) {
line = scan.nextLine();
String[] elements = line.split(',');
int elementCount = 0;
for(String element : elements) {
int elementValue = Integer.parseInt(element);
spaces[rowNumber][elementCount] = elementValue;
elementCount++;
}
rowNumber++;
}
} // you know what goes afterwards
Since it is a file which is read line by line, read each line using a delimiter ",".
So Here you just create a new scanner object passing each line using delimter ","
Code looks like this, in first for loop
for(int i = 0; i < 10; i++)
{
Scanner newScan=new Scanner(scan.nextLine()).useDelimiter(",");
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = newScan.nextInt();
}
}
Use the useDelimiter method in Scanner to set the delimiter to "," instead of the default space character.
As per the sample input given, if the next row in a 2D array begins in a new line, instead of using a ",", multiple delimiters have to be specified.
Example:
scan.useDelimiter(",|\\r\\n");
This sets the delimiter to both "," and carriage return + new line characters.
Why use a scanner for a file? You already have a BufferedReader:
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
Now you can read the file line by line. The tricky bit is you want an array of int
int[][] spaces = new int[10][10];
String line = null;
int row = 0;
while ((line = reader.readLine()) != null)
{
String[] array = line.split(",");
for (int i = 0; i < array.length; i++)
{
spaces[row][i] = Integer.parseInt(array[i]);
}
row++;
}
The other approach is using a Scanner for the individual lines:
while ((line = reader.readLine()) != null)
{
Scanner s = new Scanner(line).useDelimiter(',');
int col = 0;
while (s.hasNextInt())
{
spaces[row][col] = s.nextInt();
col++;
}
row++;
}
The other thing worth noting is that you're using an int[10][10]; this requires you to know the length of the file in advance. A List<int[]> would remove this requirement.

Insert line by line data in txt file with arraylist

My program is about contacts.
When a Doctor for an example insert name,surname,telephone, everytime he wants to save the data into txt file then output will be:
somename
somesurname
sometelephone
somename
somesurname
sometelephone
...
Right now i did the output will be only in one line:
somename somesurname sometelephone as you can see at the code:
if(text.equals("Save")) {
try {
ArrayList<String> contactsinformations=new ArrayList<>();
String name=tname.getText();
String surname=tsurname.getText();
String telephone=ttelephone.getText();
contactsinformations.add(0,name+" ");
contactsinformations.add(1,surname+" ");
contactsinformations.add(2,telephone+" ");
FileWriter outFile = new FileWriter("Contacts.txt");
BufferedWriter outStream = new BufferedWriter(outFile);
for(int i=0; i<contactsinformations.size(); i++)
outStream.write(String.valueOf(contactsinformations.get(i)));
outStream.close();
JOptionPane.showMessageDialog(this,"Data saved.");
} catch(IOException e) {
System.out.println("ERROR IN FILE");
}
}
I use for loop to get the size of the ArrayList but trying to figure out how can I insert the informations in different line.
WARNING: UPDATED QUESTION!
Question solved with just a true!
if(text.equals("Save")) {
try
{
ArrayList<String> contactsinformations=new ArrayList<>();
contactsinformations.add(tname.getText());
contactsinformations.add(tsurname.getText());
contactsinformations.add(ttelephone.getText());
FileWriter outFile = new FileWriter("Contacts.txt",true);
BufferedWriter outStream = new BufferedWriter(outFile);
for (int i = 0; i < contactsinformations.size(); i++) {
outStream.write(contactsinformations.get(i));
outStream.newLine();
}
JOptionPane.showMessageDialog(this,"Data saved.");
outStream.close();
}
Use :
outStream.write(contactsinformations.get(i) + "\n");
Here \n signifies the new line.
As ArrayList preserves insertion order you don't need to precise the index and you can omit the useless variables name, surname, telephone :
contactsinformations.add(tname.getText());
contactsinformations.add(tsurname.getText());
contactsinformations.add(ttelephone.getText());
As the type of the ArrayList is String you don't need the valueOf method :
for (int i = 0; i < contactsinformations.size(); i++) {
outStream.write(contactsinformations.get(i));
outStream.newLine();
}
The PrintWriter class has a method to do both in one call (combine with for-each loop here) :
PrintWriter pw = new PrintWriter(outFile);
for (String contactsinformation : contactsinformations) {
pw.println(contactsinformation);
}
Convert to CharArray and the write BufferedWriter :
for(int i=0; i< contactsinformations.size(); i++) {
String str = contactsinformations.get(i) + "\n";
outStream.write(str.toCharArray(), 0, str.length());
}
or write the String by using offset and length the same way as above:
for(int i=0; i< contactsinformations.size(); i++) {
String str = contactsinformations.get(i) + "\n";
outStream.write(str, 0, str.length());
}
outStream.write(contactsinformations.stream()
.collect(Collectors.joining(System.lineSeparator())));

Writer dont writing in file but only create it

Im working on converter. I load file, start reading date from it and creating directories by year, month and day(+ another one dir) in witch ends are those converted text files. Everything is fine while creating those directories but in text files is nothing or only chunk of it.
public static void convertFile(File fileToConvert, File whereToSave, long shift) {
BufferedReader reader = null;
BufferedWriter writer = null;
String oldDate = "";
String newDate = "";
boolean boolDate = true;
try {
for (File file : fileToConvert.listFiles()) {
reader = new BufferedReader(new FileReader(file));
boolean block = true;
String line = "";
int lineCounter = 0;
while ((line = reader.readLine()) != null) {
if (lineCounter==0) {
block = true;
} else {
block = false;
}
line = line.replaceAll("[^0-9-,:+NaN.]", "");
String[] data = line.split(",");
if (block) {
data[0] = data[0].substring(0, 10) + " " + data[0].substring(10);
data[0] = SimulatorForRealData.timeShift(data[0], shift);
// ====================================================================================
newDate = data[0].substring(0, 4) + " " + data[0].substring(5, 7) + " "
+ data[0].substring(8, 10);
String savingIn = SimulatorForRealData.createDirs(whereToSave.toString(),
data[0].substring(0, 4), data[0].substring(5, 7), data[0].substring(8, 10));
File f = new File(savingIn + "\\" + FILE_NAME + ".log");
if (!newDate.equals(oldDate) && boolDate == false) {
writer.close();
boolDate = true;
} else {
oldDate = newDate;
boolDate = false;
}
writer = new BufferedWriter(new FileWriter(f));
// =====================================================================================
writer.write("<in date=\"" + data[0].substring(0, 10) + "T" + data[0].substring(11)
+ "\" t=\"1\" >\n");
writer.write(data[0] + "\n");
writer.write(0 + " " + 0 + " " + 0 + "\n");
for (int x = 0; x <= 10; x++) {
writer.write("NaN" + " ");
}
writer.write("\n");
for (String s : data) {
if (s.equals(data[0])) {
continue;
}
writer.write(s + ";");
}
writer.write("\n");
} else {
for (String s : data) {
writer.write(s + ";");
}
writer.write("\n");
}
lineCounter++;
if (lineCounter == 118) {
lineCounter = 0;
writer.write("</in>\n\n");
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is method where i perform it. Can someone help me. I tried different "writers" and nothing. I have suspicious that it will be problem in closing file but i dont know for sure.
I think you should close every writer you created, not only last one.
for (File file : fileToConvert.listFiles()) {
reader = new BufferedReader(new FileReader(file));
...
writer = new BufferedWriter(new FileWriter(f));
while ((line = reader.readLine()) != null) {
....
}
writer.close();
}
writer flushes all changes on disk only when buffer is overflowed or it is closed.
I see two main problems:
You create a file every time you read a line. You should put it outside the loop (or loops, if you want only one file)
Always data is written with the same filename. It should have different filenames if you make a file for every file read.

Read a particular info and write to a txt file using java

am new to java programming I need a program to read a certain information from a file and select the particular informationwhich is needed and then write this particular information into a text file .
{
BufferedReader in = new BufferedReader (newFileReader("C:/Users/ngorentl/"));
String info = "";
String info1 = "";
int startLine = 111 ;
int endLine = 203 ;
int sl = 221;
int el =325;
// reading only the specific info which is needed and that is printing in the console
for (int i = 0; i < startLine; i++) { info = in.readLine(); }
for (int i = startLine; i < endLine + 1; i++) {
info = in.readLine();
System.out.println(info);
}
for (int j = 203; j < sl; j++) { info1 = in.readLine(); }
for (int j = sl; j < el + 1; j++) {
info1 = in.readLine();
System.out.println(info1);
}
// having a problem from here i dont know whether this is the correct approach
File fin = new File(info); // getting an error here
FileInputStream fis = new FileInputStream(fin);
BufferedReader is = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fos = new FileOutputStream("hh.txt");
OutputStreamWriter osw= new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(osw);
String aLine = null;
while ((aLine = is.readLine()) != null) {
bw.write(aLine);
bw.newLine();
bw.flush();
bw.close();
is.close();
}
in.close();
}
File fin = new File(String fileName) is the correct syntax.
eg.
File fin = new File("C:\abc.txt");
[UPDATE]
Assuming your question is about writing a String to file.
In Java 7
try( PrintWriter out = new PrintWriter( "filename.txt" ) ){
out.println( info);
}
In Java 6 or below, use
try {
BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
out.write(info);
out.close();
}
catch (IOException e)
{
System.out.println("Exception ");
}
and possible correction of your code, so variable info has all that information
for (int i = startLine; i < endLine + 1; i++) {
info += in.readLine();
}
System.out.println(info);

How can i multiply all the numbers by 10 in java file I/O

Okay, so I have to Write a program to create a file named Lab13.txt. Write ten integers ranging [0, 99] created randomly into the file using text I/O. Integers are separated by spaces in the file. Read the data back from the file and display them on the console.
I've done this part already, but next I have to take those numbers in that file, create a new file, multiply all the numbers in the Lab13.txt file, and store them in the new file. My problem is when i create the new file, I'm only able to get it to multiply the last number printed from the Lab13.txt file. How do i get it to multiply all the numbers in Lab13.txt file by 10 and print them? This is probably a really simple solution and I feel so dumb for not being able to figure it out. Creating files is the new thing we're learning and my teacher is little to no help. :(
import java.io.*;
public class Lab13 {
public static void main(String ar[]) {
String toWrite = "";
int x=0;
try {
File file=new File("Lab13.txt");
FileWriter filewriter=new FileWriter(file);
BufferedWriter writer=new BufferedWriter(filewriter);
for(int i=0;i<10;i++) {
x=(int)(Math.random()*100);
writer.write(" "+x);
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
try {
File file1=new File("Lab13.txt");
FileReader filereader=new FileReader(file1);
BufferedReader reader=new BufferedReader(filereader);
String y;
while((y=reader.readLine())!=null) {
System.out.println(y);
toWrite += ("" + x*10);
System.out.println(toWrite);
}
File output = new File("lab13_scale.txt");
if(!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter= new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
You're never reading individual numbers from that line. And the x you multiplied with 10 was the last number you randomly generated in previous loop. That's why the problem.
Remove line -
toWrite += ("" + x*10);
Replace with -
String numArray = y.split(" ");
for (int i=0; i<numArray.length; i++) {
int newNum = Integer.parseInt(numArray[i]) * 10;
toWrite += ("" + newNum);
}
Your problem is here:
while((y=reader.readLine())!=null) {
System.out.println(y);
toWrite += ("" + x*10);
System.out.println(toWrite);
}
What reader.readLine() tells the reader to do is look for every newline character "\n" and process the chunks of text in between, and since you didnt add any, it treats the whole file as a single chunk.
What you can do instead is read the entire contents of the file into a string and then split it with the space delimiter (below is untested code):
String s = reader.readLine();
String[] allNumbers = s.split(" ");
for(String number : allNumbers) {
int currentNumber = Integer.parseInt(number);
bWriter.write(String.valueOf(currentNumber * 10) + " ");
}
public void multiply() throws Exception{
//reading from existing file
BufferedReader br = new BufferedReader(new FileReader("Lab13.txt"));
String l = br.readLine(); //assuming from your code that there is only one line
br.flush();
br.close();
String[] arr = l.split(" ");
//writing into new_file.txt
BufferedWriter bw = new BufferedWriter(new FileWriter("new_file.txt"));
for(String a : arr){
bw.write((Integer.parseInt(a)*10) + " ");
}
bw.flush();
bw.close();
}
Just call this method. Should work. You basically need to split the String using space. once that done, parsing each String into Integer and multiplying. and again storing.
package com.test;
import java.io.*;
public class Lab13
{
public static void main(String ar[])
{
String toWrite = "";
int x = 0;
try
{
File file = new File("Lab13.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(filewriter);
for (int i = 0; i < 10; i++)
{
x = (int) (Math.random() * 100);
writer.write(" " + x);
}
writer.close();
} catch (IOException e)
{
e.printStackTrace();
}
try
{
File file1 = new File("Lab13.txt");
FileReader filereader = new FileReader(file1);
BufferedReader reader = new BufferedReader(filereader);
String y;
while ((y = reader.readLine()) != null)
{
////////////////////////////////////////
//trim - delete leading spaces from y
String[] array = y.trim().split(" ");
for (int i = 0; i < array.length; i++)
{
int number = Integer.parseInt(array[i]);
System.out.println(number);
toWrite += (number * 10 + " ");
}
System.out.println(toWrite);
////////////////////////////////////////
}
File output = new File("lab13_scale.txt");
if (!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter = new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}

Categories

Resources