I am retrieving data from a file and for some reason i miss the first char every time.
my code.
public String readFile(){
String str = "Not Authenticated";
//Reading the file
try{
FileInputStream fIn = openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[isr.read()]; //str.length()
// Fill the Buffer with data from the file
try {
isr.read(inputBuffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
// Transform the chars to a String
String readString = new String(inputBuffer);
str = readString;
} catch (IOException ioe)
{return ioe.toString();}
return str;
}
the file contains the word "True"
i get "rue"
also when i create the file the first letter cannot be a capital? if i use a capital the file is never found i am guessing the two are not related.
If that file is text file then read it via BufferedReader.
StringBuilder sb=new StringBuilder();
BufferedReader br=null;
try{
br=new BufferedReader(new InputStreamReader(openFileInput(fileName));
String line=null;
while((line = br.readLine()) != null)
{
sb.append(line);
}
}catch(Exception ex){
//
}finally{
if(br!=null)
br.close();
}
return sb.toString();
char[] inputBuffer = new char[isr.read()]; //str.length()
Does this not read a character out of your reader?
EDIT: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/InputStreamReader.html
isr.read() will read a single character (ie. the first character).
To get the size of the file, you can use
long length = new File(fileName).length()
See File.length() function for details.
You can use File class to find length of a file,:
File f=new File("c:\\new\\abc.txt");
f.length(); will return size in bytes
You should also close the file opened. by isr.close();
Related
I want to read my file which is a large one byte by byte and i currently using this class for reading the file:
public class File {
public byte[] readingTheFile() throws IOException {
FileReader in = new FileReader("/Users/user/Desktop/altiy.pdf");
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
in.close();
return null;
}
} //close class
Now in my main class where my main method is i am trying to read the file and then try to pass it as parameter to another method of another class like below:
public class myMainClass {
// some fields here
File f = new File ();
public static void main (String [] a) {
try {
byte[] secret = five.readingTheFile(); // We call the method which read the file
byte[][] shar = one.calculateThresholdScheme(secret, n,k);
// some other code here . Note n and k i put their values from Eclipse
} catch (IOException e) {
e.printStackTrace();
} // close catch
} // close else
} // close main
} // close class
Now in my class where calculateThresholdScheme is
public class performAlgorithm {
// some fields here
protected byte[][] calculateThresholdScheme(byte[] secret, int n, int k) {
if (secret == null)
throw new IllegalArgumentException("null secret");
// a lot of other codes below.
But my execution stops as soon as i throw this IllegalArgumentException("null secret"); which means my file is not yet readable. I am wondering what is going wrong here but i am still not figure it out
The issue with your code lies in readingTheFile():
This is the return-statement:
return null;
Which - Captain Obvious here - returns null. Thus secret is null and the IllegalArgumentException is thrown.
If you absolutely want to stick to the BufferedReader-solution, this should solve the problem:
byte[] readingTheFile(){
byte[] result = null;
try(BufferedReader br = new BufferedReader(new FileReader(path))){
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine()) != null)
sb.append(line).append(System.getProperty("line.separator"));
result = sb.toString().getBytes();
}catch(IOException e){
e.printStackTrace();
}
return result;
}
Some general advice:
BufferedReader isn't built for the purpose of reading a file byte for byte anyways. E.g. '\n' will be ignored, since you're reading line-wise. This may cause you to corrupt data while loading. Next problem: you're only closing the FileReader in readingTheFile(), but not the BufferedReader. Always close the ToplevelReader, not the underlying one. By using try-with-resources, you're saving yourself quite some work and the danger of leaving the FileReader open, if something is coded improperly.
If you want to read the bytes from a file, use FileReader instead. That'll allow you to load the entire file as byte[]:
byte[] readingTheFile(){
byte[] result = new byte[new File(path).length()];
try(FileReader fr = new FileReader(path)){
fr.read(result , result.length);
}catch(IOException e){
e.printStackTrace();
}
return result;
}
Or alternatively and even simpler: use java.nio
byte[] readingTheFile(){
try{
return Files.readAllBytes(FileSystem.getDefault().getPath(path));
}catch(IOException e){
e.printStackTrace();
return null;
}
}
Change your Class "File" like below, this is how it will provide you the desire mechanism. I've modified the same class you have written.
public class File {
public byte[] readingTheFile() throws IOException {
java.io.File file = new java.io.File("/Users/user/Desktop/altiy.pdf");
/*FileReader in = new FileReader("/Users/user/Desktop/altiy.pdf");
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
in.close();
*/
FileInputStream fin = null;
try {
// create FileInputStream object
fin = new FileInputStream(file);
byte fileContent[] = new byte[(int) file.length()];
// Reads bytes of data from this input stream into an array of
// bytes.
fin.read(fileContent);
// returning the file content in form of byte array
return fileContent;
} catch (FileNotFoundException e) {
System.out.println("File not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading file " + ioe);
} finally {
// close the streams using close method
try {
if (fin != null) {
fin.close();
}
} catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
}
return null;
}
}
Input File:
Online_system_id
bank_details
payee
credit_limit
loan_amount
Online_system_id
bank_details
payee
credit_limit
loan_amount
Expected Output:
Online_syatem_id
bank_details
payee
credit_limit
loan_amount
proc_online_system_id
Online_syatem_id
bank_details
payee
credit_limit
loan_amount
proc_online_system_id
Below is the code given for reference.
I want to add a line after each record i.e before encountering the blank line.
What changes do I need to do?
String line;
int flag=0;
PrintStream out = new PrintStream(outputFile);
BufferedReader br = new BufferedReader(new FileReader(outputFile));
while((line=br.readLine())!=null){
if(!line.contains("proc_online_system_id")){
flag=1;
}
}
if(flag==1)
out.print("proc_online_system_id");
String line;
PrintStream out = null;
BufferedReader br = null;
try {
out = new PrintStream(new FileOutputStream(outputFile));
br = new BufferedReader(new FileReader(inputFile));
while((line=br.readLine())!=null){
if(line.trim().isEmpty()) {
out.println("proc_online_system_id"); //print what you want here, BEFORE printing the current line
}
out.println(line); //always print the current line
}
} catch (IOException e) {
System.err.println(e);
} finally {
try{
out.close();
br.close();
} catch (Exception ex) {
System.err.println(ex);
}
}
And don't forget the out.close(); and br.close(); afterwards.
This solution stores only the current line in memory, as opposed to Dakkaron's answer, which is correct, but needs to store the whole file in memory (in a StringBuilder instance), before writing to file.
EDIT: After Vixen's comment, here is the link, in case you have java 7, and you want to use try with resources in your solution.
Try this code
String line;
PrintStream out = new PrintStream(outputFile);
BufferedReader br = new BufferedReader(new FileReader(outputFile));
while((line=br.readLine())!=null){
if (!line.trim().isEmpty()){
line+="\n";
}
//System.out.println(line);
}
Buffer each block. So what you do is read the file line by line and store the content of the current block in a StringBuilder. When you encounter the empty line, append your additional data. When you did that with the whole file, write the content of the StringBuilder to the file.
String line;
int flag=0;
PrintStream out = new PrintStream(outputFile);
StringBuilder builder = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(outputFile));
while((line=br.readLine())!=null){
if(!line.contains("proc_online_system_id")){
flag=1;
}
if (line.isEmpty() && flag==1) {
flag=0;
builder.append("proc_online_system_id\n");
}
builder.append(line).append("\n");
}
out.print(builder.toString());
This is another question. So it seems that I have already set up the code with InputStream and Bufferstream to retrieve a String from a text file using this code:
// Read Text File entitled wordsEn.txt
public String readFromFile() {
String words = "";
try {
InputStream inputstream = openFileInput("wordsEn.txt");
if (inputstream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputstream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputstream.close();
words = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return words;
}
So what I want to do is store each string on each line of the text file into an array. I then want to be able to use this array to select a random string everytime I press a button.
Let me know.
Thanks
Colin
Just put below line into your class varialble
ArrayList<String> wordLineArray = new ArrayList<String>();
Than use add method array list to add each line of word into it.
wordLineArray.add(receiveString);
Use this line before appending it to previous buffer.
Now use this arraylist as per your requirment.
If it is helpful to you than don't forget to accept this answer.
Try using BreakIterator.getLineInstance(). Set the text to your "words" string, then iterate through each line, adding each line to a String[] array.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to create a Java String from the contents of a file
Is it possible to process a multi-lined text file and return its contents as a string?
If this is possible, please show me how.
If you need more information, I'm playing around with I/O. I want to open a text file, process its contents, return that as a String and set the contents of a textarea to that string.
Kind of like a text editor.
Use apache-commons FileUtils's readFileToString
Check the java tutorial here -
http://download.oracle.com/javase/tutorial/essential/io/file.html
Path file = ...;
InputStream in = null;
StringBuffer cBuf = new StringBuffer();
try {
in = file.newInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
cBuf.append("\n");
cBuf.append(line);
}
} catch (IOException x) {
System.err.println(x);
} finally {
if (in != null) in.close();
}
// cBuf.toString() will contain the entire file contents
return cBuf.toString();
Something along the lines of
String result = "";
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
// Here's where you get the lines from your file
result += dis.readLine() + "\n";
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
String data = "";
try {
BufferedReader in = new BufferedReader(new FileReader(new File("some_file.txt")));
StringBuilder string = new StringBuilder();
for (String line = ""; line = in.readLine(); line != null)
string.append(line).append("\n");
in.close();
data = line.toString();
}
catch (IOException ioe) {
System.err.println("Oops: " + ioe.getMessage());
}
Just remember to import java.io.* first.
This will replace all newlines in the file with \n, because I don't think there is any way to get the separator used in the file.
How do you read and display data from .txt files?
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
If your file is strictly text, I prefer to use the java.util.Scanner class.
You can create a Scanner out of a file by:
Scanner fileIn = new Scanner(new File(thePathToYourFile));
Then, you can read text from the file using the methods:
fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
And, you can check if there is any more text left with:
fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
Once you have read the text, and saved it into a String, you can print the string to the command line with:
System.out.print(aString);
System.out.println(aString);
The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.
In general:
Create a FileInputStream for the file.
Create an InputStreamReader wrapping the input stream, specifying the correct encoding
Optionally create a BufferedReader around the InputStreamReader, which makes it simpler to read a line at a time.
Read until there's no more data (e.g. readLine returns null)
Display data as you go or buffer it up for later.
If you need more help than that, please be more specific in your question.
I love this piece of code, use it to load a file into one String:
File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).
import java.io.*;
import java.util.Scanner;
import java.io.*;
public class TestRead
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);
/* enter filename with extension to open and read its content */
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
/* this will reference only one line at a time */
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
If you want to take some shortcuts you can use Apache Commons IO:
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)
public class PassdataintoFile {
public static void main(String[] args) throws IOException {
try {
PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
pw1.println("Hi chinni");
pw1.print("your succesfully entered text into file");
pw1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
In Java 8, you can read a whole file, simply with:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
You most likely will want to use the FileInputStream class:
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while( (character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.