Reading from a text file and storing in a String [duplicate] - java

This question already has answers here:
How do I create a Java string from the contents of a file?
(35 answers)
Closed 9 years ago.
How can we read data from a text file and store in a String variable?
is it possible to pass the filename in a method and it would return the String which is the text from the file.
What kind of utilities do I have to import? A list of statements will be great.

These are the necersary imports:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
And this is a method that will allow you to read from a File by passing it the filename as a parameter like this: readFile("yourFile.txt");
String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}

How can we read data from a text file and store in a String Variable?
Err, read data from the file and store it in a String variable. It's just code. Not a real question so far.
Is it possible to pass the filename in a method and it would return the String which is the text from the file.
Yes it's possible. It's also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won't. You don't want to do it this way.

Related

How can i read text file and store text values in data base in java? [duplicate]

This question already has answers here:
Reading a plain text file in Java
(31 answers)
Closed 5 years ago.
I have text file which i have read once user upload, how can i read using java code, can any one give some suggestion which would very helpful to me
sample file looks like below
SNR Name
1 AAR
2 BAT
3 VWE
A common pattern is to use
try (BufferedReader br = new BufferedReader(new FileReader(file)) ) {
String line;
while ((line = br.readLine()) != null) {
// process the line to insert in database.
}}
The easiest way is use Scanner() object
Scanner sc = new Scanner(new File("myFile.txt"));
use
boolean hasNext = sc.hasNext();
to know if there are more items in the file
and
String item = sc.next();
to get items secuentially.
I attach the documentation (it provides very good code examples)
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
You can use BufferedReader to read file line by line.
So, even if your file is too big, then also it will read line by line only. It won't load entire file. Declaration will be similar to this.
BufferedReader br = new BufferedReader(new FileReader(FILENAME));
And
you can use command
while ((sCurrentLine = br.readLine()) != null) { .....// process
}
to read file till end.
Obviously, you have to use seperator in file to split the records in each line. And store accordingly in java objects.
After that you can store in DB through DAO.

How to read data from file till I encounter an empty line [duplicate]

This question already has answers here:
How can I read a large text file line by line using Java?
(22 answers)
Closed 6 years ago.
Is there a way I can read multiple lines from a text file until I encounter an empty line?
For example my text file looks like this:
text-text-text-text-text-text-text-text-text-text-text-text-text-text-text-text
//This is empty line
text2-tex2-text2-tex2-text2-tex2-text2-text2
Now, I want to input text-text... till the empty line into a string. How can I do that?
check below code, 1st i have read all the lines from text file, then i have check whether file contains any blank line or not, if it contains then i break the loop.
A.text
text-text-text-text-text-text-text-text-text-text-text-text-text-text-text-text
text2-tex2-text2-tex2-text2-tex2-text2-text2
import java.util.*;
import java.io.*;
public class Test {
public static void main(String args[]){
try (BufferedReader br = new BufferedReader(new FileReader("E:\\A.txt"))) {
String line;
while ((line = br.readLine()) != null) {
if(!line.isEmpty()){
System.out.println(line);
} else {
break;
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}

Parsing text Java from PDF [duplicate]

This question already has answers here:
Advanced PDF parser for Java
(5 answers)
Closed 7 years ago.
I would like to ask, how can i parse text. I had extracted text from PDF file with PDFBox into normal text, which is output in console. For example this one:
SHA256: 51c11994540537b633cf91b276b3c34556695ed870a5d3f7451e993262a4a745
File name: ACleaner.zip
Detection ratio: 0 / 55
Analysis date: 2015­07­21 12:23:19 UTC ( 8 minutes ago )
0 0
? Analysis ? File detail ? Additional information ? Comments  0 ? Votes
MD5  fffa183f43766ed39d411cb5f48dbc87
SHA1  b0d40fbc6c722d59031bb488455f89ba086eacd9
SHA256  51c11994540537b633cf91b276b3c34556695ed870a5d3f7451e993262a4a745
I need to get some values, for example value of MD5, File name etc..how can i reach it in Java? Thanks a lot
I have tried so : in this while a i added this
String keySHA256 = "SHA256:";
private static String SHA256Value = null;
if (line.contains(keySHA256)) {
// System.out.println(line);
int length = keySHA256.length();
SHA256Value = line.substring(length);
System.out.println("SHA256 >>>>" + SHA256Value);
}
but sometimes it doesnt get right value..please help..
This could be a good example for you to start learning more about Java IO and String parsing. Google is your friend.
//uri where your file is
String fileName = "c://lines.txt";
// read the file into a buffered reader
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) { //iterate on each line of the file
System.out.println(line); // print it if you want
String[] split=line.split(" "); // split your line into array of strings, each one is a separate word that has no spaces in it.
//add any checks or extra processes here
}
} catch (IOException e) {
e.printStackTrace();
}

Java -- Need help to enhance the code

I wrote a simple program to read the content from text/log file to html with conditional formatting.
Below is my code.
import java.io.*;
import java.util.*;
class TextToHtmlConversion {
public void readFile(String[] args) {
for (String textfile : args) {
try{
//command line parameter
BufferedReader br = new BufferedReader(new FileReader(textfile));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
Date d = new Date();
String dateWithoutTime = d.toString().substring(0, 10);
String outputfile = new String("Test Report"+dateWithoutTime+".html");
FileWriter filestream = new FileWriter(outputfile,true);
BufferedWriter out = new BufferedWriter(filestream);
out.write("<html>");
out.write("<body>");
out.write("<table width='500'>");
out.write("<tr>");
out.write("<td width='50%'>");
if(strLine.startsWith(" CustomerName is ")){
//System.out.println("value of String split Client is :"+strLine.substring(16));
out.write(strLine.substring(16));
}
out.write("</td>");
out.write("<td width='50%'>");
if(strLine.startsWith(" Logged in users are ")){
if(!strLine.substring(21).isEmpty()){
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Red'>");
out.write("</textarea>");
}else{
System.out.println("else if block:");
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Green'>");
out.write("</textarea>");
} //closing else block
//out.write("<br>");
out.write("</td>");
}
out.write("</td>");
out.write("</tr>");
out.write("</table>");
out.write("</body>");
out.write("</html>");
out.close();
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
public static void main(String args[]) {
TextToHtmlConversion myReader = new TextToHtmlConversion();
String fileArray[] = {"D:/JavaTesting/test.log"};
myReader.readFile(fileArray);
}
}
I was thinking to enhance my program and the confusion is of either i should use Maps or properties file to store search string. I was looking out for a approach to avoid using substring method (using index of a line). Any suggestions are truly appreciated.
From top to bottom:
Don't use wildcard imports.
Don't use the default package
restructure your readFile method in more smaller methods
Use the new Java 7 file API to read files
Try to use a try-block with a resource (your file)
I wouldn't write continuously to a file, write it in the end
Don't catch general Exception
Use a final block to close resources (or the try block mentioned before)
And in general: Don't create HTML by appending strings, this is a bad pattern for its own. But well, it seems that what you want to do.
Edit
Oh one more: Your text file contains some data right? If your data represents some entities (or objects) it would be good to create a POJO for this. I think your text file contains users (right?). Then create a class called Users and parse the text file to get a list of all users in it. Something like:
List<User> users = User.parse("your-file.txt");
Afterwards you have a nice user object and all your ugly parsing is in one central point.

What's the difference between File and FileLoader in Java?

So I have the following code where I should read a Text File (This is just the Main Class):
import gui.MenuWindow;
import java.io.IOException;
import javax.swing.JOptionPane;
public class Assessor {
public static void main(String args[]) throws IOException {
FileLoader file = new FileLoader("Example.txt");
try{
new MenuWindow(file.loader());
} catch(Exception exc) {
JOptionPane.showMessageDialog(null, "Error Reading File");
}
}
}
Then I'd have to load the Text into a ListBox using Swing. The thing is that I've found this new code to read a Text File:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadTextFileExample {
public static void main(String[] args) {
File file = new File("test.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// show file contents here
System.out.println(contents.toString());
}
}
So I'd like to know what is the difference between the following two lines:
FileLoader file = new FileLoader("Example.txt"); //First Code
File file = new File("test.txt"); //Second Code
And... What's the StringBuffer and BufferedReader used to? Thanks!
So I'd like to know what is the difference between the following two lines:
FileLoader file = new FileLoader("Example.txt"); //First Code
File file = new File("test.txt"); //Second Code
The first creates a java.io.FileLoader which Andreas discusses. Since the javadoc says "The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate", it should never be used.
The second creates a java.io.File which is just a file path with some utility methods that can be used to read directory trees, delete, create, and move files, etc., or it can be used with FileInputStream and other classes to actually access the file contents.
And... What's the StringBuffer and BufferedReader used to? Thanks!
The StringBuffer is used to collect the contents of the file.
The BufferedReader is used to speed up reading of the file. Instead of reading one character at a time, the BufferedReader batches reads using an internal buffer.
This is an exemplary question about learning Java SE, especially regarding the java.io package. I was a bit puzzled in the beginning, but now I am quite sure that you want to compare the FileReader to the File class, which both belong to the same package java.io.
File in the Java SE API:"An abstract representation of file and directory pathnames."In other words, it is there to handle files and directories on the file system within Java. Since Java is an object-oriented language, they made a class for it. Files, i.e. binary and text files, share some attributes in common with directories, as there are: absolute, canonical path and simple name, etc.Of course, File is one of the base classes in the java.io package and many classes like FileReader make use of it for object construction.
FileReader:"Convenience class for reading character files."It comes with a handy constructor that takes a file name or file path as a String. Originally, it was meant to be constructed by a File instance. A Reader instance in general is practical to read text files, in contrast to InputStream, which is used to read binary files. A Reader instance in general is connected to a character set, e.g. "UTF-8" to translate byte to character streams.
Please also have a look at the excellent Java Tutorials provided by Oracle.
I hope the difference between File and FileReader becomes a little clearer. Especially note that there is no I/O, when you instantiate a File instance. To answer your question, the interconnection of the two classes would be:
File file = new File("test.txt"); // 1) Instaniate the file
Reader reader = new FileReader(file); // 2) Instantiate the Reader using the File instance
When you wrap a BufferedReader around a Reader instance, you can read the text file linewise, as:
BufferedReader bufferedReader = new BufferedReader(reader); // 3) Get a "buffered reader" to have access line by line.
StringBuffer comes in, when you want to chain a large number of String objects, since String objects is immutable and string operations like
String s1 = "Star ";
String s2 = "Wars";
s1 = s1 + s2;
are very costly, especially in loops, since at every addition a new String object (left side result) is created, with practically no size limits, apart from the reserved Java VM heap space.
Let me point out that you should better use the StringBuilder class, which is even faster, and is the unsynchronized counter-part of StringBuffer, introduced in the Java 5 release. The feature that StringBuffer is guaranteed to be synchronized among different Thread's is hardly ever used. I never came across it in my whole life as Java programmer.

Categories

Resources