Reading a variable number of lines from a file - java

I am trying to read a variable number of lines from a file, hopefully using InputStream object. What I'm trying to do (in a very general sense) is as follows:
Pass in long maxLines to function
Open InputStream and OutputStream for reading/writing
WHILE (not at the end of read file AND linesWritten < maxLines)
write to file
I know InputStream goes on bytes, not lines, so I'm not sure if that's a good API to use for this. If anyone has any reccomendations on what to look at in terms of a solution (other API's, different algorithm) that's be very helpful.

You can have something like this
BufferedReader br = new BufferedReader(new FileReader("FILE_LOCATION"));
while (br.readLine() != null && linesWritten < maxLines) {
//Your logic goes here
}

Have a look at these:
Buffered Reader and
Buffered Writer
//Read file into String allText
InputSream fis = new FileInputStream("filein.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line, allText = "";
try {
while ((line = br.readLine()) != null) {
allText += (line + System.getProperty("line.separator")); //Track where new lines should be for output
}
} catch(IOException e) {} //Catch any errors
br.close(); //Close reader
//Write allText to new file
BufferedWriter bw = new BufferedWriter(new FileWriter("fileout.txt"));
try {
bw.write(allText);
} catch(IOException e) {} //Catch any errors
bw.close(); //Close writer

Related

Android/java Cant read from .txt file in local storage

So i have a .txt file in local storage its a simple text file. The text is basically just a series of lines.
I am using the code below to attempt to read the text file (i verify the file exists before calling this method).
public static String GetLocalMasterFileStream(String Operation) throws Exception {
//Get the text file
File file = new File("sdcard/CM3/advices/advice_master.txt");
if (file.canRead() == true) {System.out.println("-----Determined that file is readable");}
//Read text from file
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
System.out.println("-----" + line); //for producing test output
text.append('\n');
}
br.close();
System.out.print(text.toString());
return text.toString();
}
The code produces in the log
----Determined that file is readable
But that is the ONLY output the file data is not written to the log
Also i have tried inserting before the while loop the following to attempt to just read the first line
line = br.readLine();
System.out.println("-----" + line);
That produces the following output:
-----null
Check this out getExternalStorage
File path = Environment.getExternalStorageDirectory();
File file = new File(path, "textfile.txt");
//text file is copied in sdcard for example
Try to add a lead slash in file path /sdcard/CM3/advices/advice_master.txt
File file = new File("/sdcard/CM3/advices/advice_master.txt");
Try this. Just pass the txt file name as a parameter...
public void readFromFile(String fileName){
/*
InputStream ips;
ips = getClass().getResourceAsStream(fileName);
//reading
try{
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
String line;
while ((line = br.readLine())!=null){
//reading goes here ;)
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
*/
// or try this
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
}
Let me refine my answer. You can try another way to read all lines from advice_master.txt and see what happens. It makes sure that all file contents can be read.
Charset charset = Charset.forName("ISO-8859-1");
try {
List<String> lines = Files.readAllLines(Paths.get(YOUR_PATH), charset);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e);
}

Can not write all the data to txt file

I have a problem with writing data to my .txt file. It doesn't write all the data to my .txt file. I have tried it to put everything in a array, but also that doesn't works.
My code:
BufferedWriter writer = null;
try {
String line;
Process p = Runtime.getRuntime().exec("ps -A -o pid");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
writer = new BufferedWriter(new FileWriter(" the path .."));
writer.write(line);
System.out.println(line);
}
writer.close();
input.close();
} catch (Exception err) {
err.printStackTrace();
System.out.println("Sorry!");
}
It writes only the last line of the console.
By re-creating the object without closing it during every iteration of the loop, you are discarding what you have written so far (You have to use writer.close() to save what you have written using the object).
You will need to declare writer before the loop, so change it to the following
BufferedWriter writer = null;
try {
String line;
Process p = Runtime.getRuntime().exec("ps -A -o pid");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
writer = new BufferedWriter(new FileWriter(" the path .."));
while ((line = input.readLine()) != null) {
writer.write(line);
System.out.println(line);
}
writer.close();
input.close();
} catch (Exception err) {
err.printStackTrace();
System.out.println("Sorry!");
}
Can I just ask, why were you re-declaring the writer object every iteration?

Java: while((line = bufferedReader.readLine()) != null) MISSING 2 LINES

Ignore the arguments being passed into the method.
My code:
public static void setEnabled(EntityPlayer p, Boolean b){
try{
FileReader fileReader = new FileReader(SLInfo.STORAGEFILE);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter(SLInfo.STORAGEFILE);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line = null;
boolean breakearly = false;
bufferedWriter.write("HeLlo");
bufferedWriter.newLine();
bufferedWriter.write("World!");
System.out.println("GOT TO THIS FRICKIN POINT");
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
Thread.sleep(2000);
}
bufferedReader.close();
bufferedWriter.close();
}catch(Exception e){e.printStackTrace();}
}
This is simply outputting "GOT TO THIS FRICKIN POINT" (I decided this string in my fury). I have no idea why. In my file, it shows:
"Hello"
"World"
I just don't get it.
EDIT: Cool. I didn't know that. Unfortunately, that was just a simple example that I thought would solve my problem... it didn't. Taking a look at my code below, and assuming that the file contains p.username, which is a string, on line 1, why is "got here" never printed and "did this" always printed. What I expected it to do: If p.username is on line x, it changes line x to read "p.username booleanvalue" and if p.username is not anywhere in the file, "p.username booleanvalue" is appended to the last line in the file.
public static void setEnabled(EntityPlayer p, Boolean b){
try{
FileReader fileReader = new FileReader(SLInfo.STORAGEFILE);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter(SLInfo.STORAGEFILE);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line = null;
boolean breakearly = false;
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
if (line.contains(p.username)){
System.out.println("Got here");
bufferedWriter.write(p.username + " " + Boolean.toString(b));
bufferedWriter.newLine();
bufferedWriter.flush();
breakearly = true;
break;
}
}
bufferedWriter.flush();
System.out.println(breakearly);
if (!breakearly){
System.out.println("did this");
bufferedWriter.write(p.username + " " + Boolean.toString(b));
bufferedWriter.newLine();
bufferedWriter.flush();
}
bufferedReader.close();
bufferedWriter.close();
}catch(Exception e){e.printStackTrace();}
}
(Yes, I know I have excessive flushes)
This is where the Buffered in BufferedWriter comes in.
You write two lines, which due to buffering are stored in memory.
You then read from the file, which has nothing written to it yet.
Then you close the writer, causing the buffers to flush, adding the contents to the file.
To force flushing before you read, you can use bufferedWriter.flush(), or close it.
You are not flushing your output:
Try this code
boolean breakearly = false;
bufferedWriter.write("HeLlo");
bufferedWriter.newLine();
bufferedWriter.write("World!");
// flush
bufferedWriter.flush();
// close the bufferwriter
bufferedWriter.close();
now read your file again
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
Thread.sleep(2000);
}
When you write to file, you acctualy write to file cache, try calling bufferedWriter.close() to save all changes.
write these lines:
bufferedWriter.flush(); // flush
// now close the bufferwriter
bufferedWriter.close();
now read your file again
while((line = bufferedReader.readLine()) != null){
// your reading code
}

Importing a text file in Android SDK

I've been trying to read a file for the last few days and have tried following other answers but have not succeeded. This is the code I currently have to import the text file:
public ArrayList<String> crteDict() {
try {
BufferedReader br = new BufferedReader
(new FileReader("/program/res/raw/levels.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] linewrds = line.split(" ");
words.add(linewrds[0].toLowerCase());
// process the line.
}
br.close();
}
catch (FileNotFoundException fe){
fe.printStackTrace();
It is meant to read the text file and just create a long Array of words. It keeps ending up in the FileNotFoundException.
Please let me know any answers.
Thanks!
IF your file is stored in the res/raw folder of the android project, you can read it as follows, this code must be inside an Activity class, as this.getResources() refers to Context.getResources():
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(R.raw.levels);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}

Writing the contents to a file from input stream

I want to write the inputstream into a file in java. How to write the contents into a text file in java?
try {
BufferedReader in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
//I want to write the content to a file line by line here
while (!in.ready()) {}
System.out.print("'\n");
in.close();
}
FileWriter fstream = new FileWriter("fileName");
BufferedWriter fbw = new BufferedWriter(fstream);
while ((line = in.readLine()) != null) {
fbw.write(line + "\n");
}

Categories

Resources