Multiple Operations with FileInputStream - java

I have a Java class to read a file and set some data to a class. I have a class
FileMetadata.java
public class FileMetadata implements Serializable {
private String location;
private Double size;
private String content;
private List<String> lines;
private String md5Digest;
//parameterized constructor
//getters and setters
}
After reading the file, I want to set the values in this class.
This is my method to read the file.
FileUtil.java
public static void readFile(File file) throws IOException {
FileInputStream fis = null;
List<String> fileLines = new ArrayList<String>();
try {
fis = new FileInputStream(file);
StringBuilder sb = new StringBuilder();
StringBuilder sbLine = new StringBuilder();
int ch;
while ((ch = fis.read()) != -1) {
String line = "" + (char) ch;
sb.append(line);
if(line.matches("(\r|\n)")) {
fileLines.add(sbLine.toString());
sbLine.setLength(0);
} else {
sbLine.append(line);
}
}
String md5 = DigestUtils.md5Hex(fis);
System.out.println(md5);
System.out.println(sb.toString());
System.out.println(getFileSizeInKB(file));
for(String str : fileLines) {
System.out.println(str);
}
} finally {
if (fis != null) {
fis.close();
}
}
}
But the list is not coming up properly as it is adding an empty string after each line, because the file next line is "\r\n". The second time it is adding empty StringBuilder so the list is getting extra empty string after each line.
I could try checking the length of it before adding to List. But if the file contains an empty line, I want to add to the list.

You can try using BufferedReader class.
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line=br.readLine())!=null) {
..............
}
br.close();
FileInputStream fis = new FileInputStream(file);
String md5 = DigestUtils.md5Hex(fis);
fis.close();
(There is not exception handling in the example).

Related

How to extract starting of a String in Java

I have a text file with more than 20,000 lines and i need to extract specific line from it. The output of this program is completely blank file.
There are 20,000 lines in the txt file and this ISDN line keeps on repeating lots of time each with different value. My text file contains following data.
RecordType=0(MOC)
sequenceNumber=456456456
callingIMSI=73454353911
callingIMEI=85346344
callingNumber
AddInd=H45345'1
NumPlan=H34634'2
ISDN=94634564366 // Need to extract this "ISDN" line only
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file = null;
String line = "";
String line2 = "";
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
while ((line = reader.readLine()) != null) {
// extract logic starts here
if (line.startsWith("ISDN") == true) {
System.out.println("hello");
returnValue += line + "\n";
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException("File not found");
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return returnValue;
}
We will assume that you use Java 7, since this is 2014.
Here is a method which will return a List<String> where each element is an ISDN:
private static final Pattern ISDN = Pattern.compile("ISDN=(.*)");
// ...
public List<String> getISDNsFromFile(final String fileName)
throws IOException
{
final Path path = Paths.get(fileName);
final List<String> ret = new ArrayList<>();
Matcher m;
String line;
try (
final BufferedReader reader
= Files.newBufferedReader(path, StandardCharsets.UTF_8);
) {
while ((line = reader.readLine()) != null) {
m = ISDN.matcher(line);
if (m.matches())
ret.add(m.group(1));
}
}
return ret;
}

Java read certain line from txt file

I want to read the 2nd line of text from a file and have that put into an array. I already have it working on the first line.
[ Code removed as requested ]
The while loop above shows how I read and save the 1st line of the text file into an array. I wish to repeat this process from the 2nd line only into a different array.
File Content:
Sofa,Armchair,Computer Desk,Coffee Table,TV Stand,Cushion,Bed,Mattress,Duvet,Pillow
599.99,229.99,129.99,40.00,37.00,08.00,145.00,299.99,24.99,09.99
Just get rid of the first readLine() call, and move the String.split() call into the loop.
Simply use the BufferedReader class to read the entire file and then manipulate the String output.
Something along these lines
public static String readFile(String fileName) throws IOException {
String toReturn = "";
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("test.txt"));
while ((sCurrentLine = br.readLine()) != null) {
toReturn = toReturn+"\n"+sCurrentLine;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return toReturn;
}
would yield a String which can then be easily used.
public static void main(String[] args)
{
String filePath = args[0];
String[] lineElements = getLine(filePath,2).split(",");
}
public static String getLine(String path,int line)
{
List<String> cases = new ArrayList<String>();
try{
BufferedReader br = new BufferedReader(new FileReader(path));
String currLine = "";
while((currLine = br.readLine()) != null){
cases.add(currLine);
}
}catch(IOException ex){
ex.printStackTrace();
}
return cases.get(line - 1);//2nd line
}

Code for reading from a text file doesn't work

I am new to Java and it has all been self-taught. I enjoy working with the code and it is just a hobby, so, I don't have any formal education on the topic.
I am at the point now where I am learning to read from a text file. The code that I have been given isn't correct. It works when I hardcode the exact number of lines but if I use a "for" loop to sense how many lines, it doesn't work.
I have altered it a bit from what I was given. Here is where I am now:
This is my main class
package textfiles;
import java.io.IOException;
public class FileData {
public static void main(String[] args) throws IOException {
String file_name = "C:/Users/Desktop/test.txt";
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int nLines = file.readLines();
int i = 0;
for (i = 0; i < nLines; i++) {
System.out.println(aryLines[i]);
}
}
}
This is my class that will read the text file and sense the number of lines
package textfiles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
int numberOfLines = 0;
String aLine;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
int i;
for (i = 0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
}
Please, keep in mind that I am self-taught; I may not indent correctly or I may make simple mistakes but don't be rude. Can someone look this over and see why it is not sensing the number of lines (int numberOfLines) and why it won't work unless I hardcode the number of lines in the readLines() method.
The problem is, you set the number of lines to read as zero with int numberOfLines = 0;
I'd rather suggest to use a list for the lines, and then convert it to an array.
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
//int numberOfLines = 0; //this is not needed
List<String> textData = new ArrayList<String>(); //we don't know how many lines are there going to be in the file
//this part should work akin to the readLines part
String aLine;
while ((aLine = bf.readLine()) != null) {
textData.add(aLine); //add the line to the list
}
textReader.close();
return textData.toArray(new String[textData.size()]); //convert it to an array, and return
}
}
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
textData is an empty array. The following for loop wont do anything.
Note also that this is not the best way to read a file line by line. Here is a proper example on how to get the lines from a text file:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
I also suggest that you read tutorials on object oriented concepts.
This is a class that I wrote awhile back that I think you may find helpful.
public class FileIO {
static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while ((line = input.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
} finally {
input.close();
}
} catch (IOException ex) {
}
return contents.toString();
}
static public File OpenFile()
{
return (FileIO.FileDialog("Open"));
}
static private File FileDialog(String buttonText)
{
String defaultDirectory = System.getProperty("user.dir");
final JFileChooser jfc = new JFileChooser(defaultDirectory);
jfc.setMultiSelectionEnabled(false);
jfc.setApproveButtonText(buttonText);
if (jfc.showOpenDialog(jfc) != JFileChooser.APPROVE_OPTION)
{
return (null);
}
File file = jfc.getSelectedFile();
return (file);
}
}
It is used:
File file = FileIO.OpenFile();
It is designed specifically for reading in files and nothing else, so can hopefully be a useful example to look at in your learning.

Weird character at the beginning of the file?

When reading from a file, the first line that I read has a weird character (using BufferedReader). How do I delete this character? I know I can do it manually, but I want to do it the right way.
Picture(NetBeans output)
Using the relevant code from the link that the OP provided, here is an answer to the question which works as intended.
import java.io.*;
public class UTF8ToAnsiUtils {
// FEFF because this is the Unicode char represented by the UTF-8 byte order mark (EF BB BF).
public static final String UTF8_BOM = "\uFEFF";
public static void main(String args[]) {
try {
if (args.length != 2) {
System.out
.println("Usage : java UTF8ToAnsiUtils utf8file ansifile");
System.exit(1);
}
boolean firstLine = true;
FileInputStream fis = new FileInputStream(args[0]);
BufferedReader r = new BufferedReader(new InputStreamReader(fis,
"UTF8"));
FileOutputStream fos = new FileOutputStream(args[1]);
Writer w = new BufferedWriter(new OutputStreamWriter(fos, "Cp1252"));
for (String s = ""; (s = r.readLine()) != null;) {
if (firstLine) {
s = UTF8ToAnsiUtils.removeUTF8BOM(s);
firstLine = false;
}
w.write(s + System.getProperty("line.separator"));
w.flush();
}
w.close();
r.close();
System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private static String removeUTF8BOM(String s) {
if (s.startsWith(UTF8_BOM)) {
s = s.substring(1);
}
return s;
}
}

How to convert FileInputStream into string in java?

In my java project, I'm passing FileInputStream to a function,
I need to convert (typecast FileInputStream to string),
How to do it.??
public static void checkfor(FileInputStream fis) {
String a=new String;
a=fis //how to do convert fileInputStream into string
print string here
}
You can't directly convert it to string. You should implement something like this
Add this code to your method
//Commented this out because this is not the efficient way to achieve that
//StringBuilder builder = new StringBuilder();
//int ch;
//while((ch = fis.read()) != -1){
// builder.append((char)ch);
//}
//
//System.out.println(builder.toString());
Use Aubin's solution:
public static String getFileContent(
FileInputStream fis,
String encoding ) throws IOException
{
try( BufferedReader br =
new BufferedReader( new InputStreamReader(fis, encoding )))
{
StringBuilder sb = new StringBuilder();
String line;
while(( line = br.readLine()) != null ) {
sb.append( line );
sb.append( '\n' );
}
return sb.toString();
}
}
public static String getFileContent(
FileInputStream fis,
String encoding ) throws IOException
{
try( BufferedReader br =
new BufferedReader( new InputStreamReader(fis, encoding )))
{
StringBuilder sb = new StringBuilder();
String line;
while(( line = br.readLine()) != null ) {
sb.append( line );
sb.append( '\n' );
}
return sb.toString();
}
}
Using Apache commons IOUtils function
import org.apache.commons.io.IOUtils;
InputStream inStream = new FileInputStream("filename.txt");
String body = IOUtils.toString(inStream, StandardCharsets.UTF_8.name());
Don't make the mistake of relying upon or needlessly converting/losing endline characters. Do it character by character. Don't forget to use the proper character encoding to interpres the stream.
public String getFileContent( FileInputStream fis ) {
StringBuilder sb = new StringBuilder();
Reader r = new InputStreamReader(fis, "UTF-8"); //or whatever encoding
int ch = r.read();
while(ch >= 0) {
sb.append(ch);
ch = r.read();
}
return sb.toString();
}
If you want to make this a little more efficient, you can use arrays of characters instead, but to be honest, looping over the characters can be still quite fast.
public String getFileContent( FileInputStream fis ) {
StringBuilder sb = new StringBuilder();
Reader r = new InputStreamReader(fis, "UTF-8"); //or whatever encoding
char[] buf = new char[1024];
int amt = r.read(buf);
while(amt > 0) {
sb.append(buf, 0, amt);
amt = r.read(buf);
}
return sb.toString();
}
From an answer I edited here:
static String convertStreamToString(java.io.InputStream is) {
if (is == null) {
return "";
}
java.util.Scanner s = new java.util.Scanner(is);
s.useDelimiter("\\A");
String streamString = s.hasNext() ? s.next() : "";
s.close();
return streamString;
}
This avoids all errors and works well.
Use following code ---->
try {
FileInputStream fis=new FileInputStream("filename.txt");
int i=0;
while((i = fis.read()) !=-1 ) { // to reach until the laste bytecode -1
System.out.print((char)i); /* For converting each bytecode into character */
}
fis.close();
} catch(Exception ex) {
System.out.println(ex);
}

Categories

Resources