I have a bunch of strings that I'm writing to a file:
private void writeScoreToFile(BlastScore result)
{
try{
FileWriter fstream = new FileWriter(getFilesDir() + CaptureActivity.BLAST_SCORES,true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(Integer.toString(result.getBlastScore()));
out.close();
}catch (Exception e){
System.err.println("Write Error: " + e.getMessage());
}
}
I would like to read it back in as a List.
private List<String> getArrayFromFile(String filename) throws IOException
{
FileReader fileReader = new FileReader(getFilesDir() + filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines;
}
The list that is being written is:
100
96
100
96
100
When I print the List it looks like
10-28 21:22:31.130: I/System.out(936): Last Score: 1009610096100
Here is the code I am using to print it:
try {
List<String> blastScores = getArrayFromFile(CaptureActivity.BLAST_SCORES);
System.out.println("Last Score: " + blastScores.get(blastScores.size()-1));
} catch (IOException e) {
// TODO Auto-generated catch block
System.err.println("Read Error: " + e.getMessage());
}
I'm trying to get the n-1 element.
I'm not sure what I'm doing wrong.
When you are writing the Integers or Integer Strings you are not putting a new line character after each output. Hence, your file has only one line of data, which line you are getting as a continuous String...
To fix, add a line separator like write.newLine() in between separate write() calls.
The code which writes the scores uses
out.write(Integer.toString(result.getBlastScore()));
This means that if the method is called with scores 12, 100 and 2, your file will look like
121002
since you don't write any separator. How do you want to parse this into three numbers correctly?
Use a PrintWriter that wraps the BufferedWriter, and use its println method to write the score.
Note that writing the scores one by one by opening the file and closing it each time won't be very fast. BTW, using a BufferedWriter just to write a single integer won't gain any benefit. You also have bad exception handling : the streams and readers/writers should always be closed in a finally block.
In your writeScoreToFile function I don't see any new line or any sort of delimiter that would separate each score being written.
In that case your file would in fact contain 1009610096100 on a single line and the loop inside getArrayFromFile would only be executed once:
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
Therefore your List<String> only contains 1 element and the code blastScores.get(blastScores.size()-1) will get the last and only element, that obviously being 1009610096100.
Related
My code works fine however it prints the values side by side instead of under each other line by line. Like this:
iatadult,DDD,
iatfirst,AAA,BBB,CCC
I have done a diligent search on stackoverflow and none of my solution's seem to work. I know that I have to make the change while the looping is going on. However none of the examples I have seen have worked. Any further understanding or techniques to achieve my goal would be helpful. Whatever I am missing is probably very small. Please help.
String folderPath1 = "C:\\PayrollSync\\client\\client_orginal.txt";
File file = new File (folderPath1);
ArrayList<String> fileContents = new ArrayList<>(); // holds all matching client names in array
try {
BufferedReader reader = new BufferedReader(new FileReader(file));// reads entire file
String line;
while (( line = reader.readLine()) != null) {
if(line.contains("fooa")||line.contains("foob")){
fileContents.add(line);
}
//---------------------------------------
}
reader.close();// close reader
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(fileContents);
Add a Line Feed before you add to fileContents.
fileContents.add(line+"\n");
By printing the list directly as you are doing you are invoking the method toString() overridden for the list which prints the contents like this:
obj1.toString(),obj2.toString() .. , objN.toString()
in your case the obj* are of type String and the toString() override for it returns the string itself. That's why you are seeing all the strings separated by comma.
To do something different, i.e: printing each object in a separate line you should implement it yourself, and you can simply append the new line character('\n') after each string.
Possible solution in java 8:
String result = fileContents.stream().collect(Collectors.joining('\n'));
System.out.println(result);
A platform-independent way to add a new line:
fileContents.add(line + System.lineSeparator);
Below is my full answer. Thanks for your help stackoverflow. It took me all day but I have a full solution.
File file = new File (folderPath1);
ArrayList<String> fileContents = new ArrayList<>(); // holds all matching client names in array
try {
BufferedReader reader = new BufferedReader(new FileReader(file));// reads entire file
String line;
while (( line = reader.readLine()) != null) {
String [] names ={"iatdaily","iatrapala","iatfirst","wpolkrate","iatjohnson","iatvaleant"};
if (Stream.of(names).anyMatch(line.trim()::contains)) {
System.out.println(line);
fileContents.add(line + "\n");
}
}
System.out.println("---------------");
reader.close();// close reader
} catch (Exception e) {
System.out.println(e.getMessage());
}
I have data file “ReadFile1.txt”. I want to read each data from ReadFile1.txt and manipulate those data then write the results in another file “WriteFile2.txt”. Here is my function. The problem is it only reads 2nd,4th, and so on and does write only 2nd result. What’s wrong in this code? I appreciate your help.
public void doManipulate() throws NumberFormatException, IOException {
int multiple = 10;
try {
FileInputStream file = new FileInputStream("ReadFile1.txt");
InputStreamReader input = new InputStreamReader(file);
BufferedReader reader = new BufferedReader(input);
String data1;
while ((data1 = reader.readLine()) != null) {
int data2 = 0;
data1 = reader.readLine();
data2 = Integer.parseInt(data1);
int compressedFrames = data2*multiple;
File file2 = new File("WriteFile2.txt");
FileWriter writer = new FileWriter(file2);
writer.write(String.valueOf(compressedFrames) + "\n");
writer.flush();
writer.close();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
You're calling reader.readLine() twice for every iteration of the while loop - the first time is in the loop declaration, which reads every odd line, and the second is just a couple of lines down (data1 = reader.readLine();). The second call is blowing away anything read by the first before you have a chance to parse it. Removing the second call should fix the "every other line" issue.
Another issue is that you're closing the writer at every iteration of the while loop - don't close the writer until the while loop is done or your output file will only have the first parsed data element in it after your program closes.
I am facing some problem while reading the contents of file.
Although program is reading contents, it is skipping odd line data from file.
Example of file:
Czech Republic____06092015_091108
France____06092015_060256
Greece____06092015_073528
Hungary____06092015_093424
India____06092015_120741
Indonesia____06092015_140940
Kazakhstan____06092015_095945
Mexico____06092015_061522
Turkey____06092015_100457
But the output is:
java.io.DataInputStream#1909752
France____06092015_060256
Hungary____06092015_093424
Indonesia____06092015_140940
Mexico____06092015_061522
I don't understand why it is giving output as in this format.
I have line separator in input file, can it be causing the problem?
public class tst {
// Main method
public static void main(String args[]) {
// Stream to read file
FileInputStream fin;
int k = 0;
try {
// Open an input stream
fin = new FileInputStream(
"C:/Users/BOT2/Desktop/MC_WIth_DATA_Files.txt");
DataInputStream in1 = new DataInputStream(fin);
// Read a line of text
System.out.println(new DataInputStream(fin));
// Close our input stream
BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
while (br1.readLine() != null) {// System.out.println(k);k++;
System.out.println(br1.readLine());
}
br1.close();
fin.close();
}
// Catches any error conditions
catch (IOException e) {
System.err.println("Unable to read from file");
System.exit(-1);
}
}
}
You have two errors. First, you print out the dataStream object for some reason. Get rid of :
// Read a line of text
System.out.println( new DataInputStream(fin) );
Next, you throw away lines of text. Try this instead:
String line;
while ((line = br1.readLine()) != null){
System.out.println(line);
}
The first line is printed by:
System.out.println( new DataInputStream(fin) );
it gives you te result of new DataInputStream(fin).toString()
The next lines are printed in this format, bacause you read two lines per loop:
first line while (br1.readLine() != null){ and second line: System.out.println(br1.readLine()); }
So you have to change your code to:
String line;
while ((line =br1.readLine()) != null){//System.out.println(k);k++;
System.out.println(line );
}
br1.close();
fin.close();
The problem is here
while (br1.readLine() != null){
System.out.println(br1.readLine());
}
br1.close();
fin.close();
}
When you call br1.readLine() it reads out the current line and move the cursor position to point to the next line. You are calling this method twice causing you to skip alternative lines. You should call readLine() only once per iteration.
i suggest cleaner code so you and whoever reads it will understand immediately what you are doing.
Try this :
Scanner read;
try{
read=new Scanner(new FileReader("your path"));
while(read.hasNext()){
System.out.println(read.nextLine);
}
read.close();
}
catch(FileNotFoundException e){
}
I have a problem in java and i dont understand why, since i think i am doing text-book stuff.
An overview in what of want to do is:
I want to create a file that contains in each line two strings: documentPath, documentID (in this format: "documentPath;documentID;")
I want to be able to add lines at the end of the file and load the file to a Java Data Structure, lets say a HashSet.
Each time i want to add a new line, i load all the file in a HashSet, check if the line i want to add is not already there and eventually add it at the end. (small number of data - don't care about efficiency)
The code
Add file:
public void addFile(String documentPath) {
this.loadCollection(); //METHOD IS NOT CONTINUING: ERROR HERE
if (!documentsInfo.contains(documentPath)) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(this.collectionFile, true)));
DocumentInfo documentInfo = new DocumentInfo(documentPath, ++this.IDcounter);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Load file:
public void loadCollection() {
if (loaded) {return;}
BufferedReader br;
try {
br = new BufferedReader(new FileReader(collectionFile));
String line;
while ( (line = br.readLine())!= null ) { //PROBLEM HERE
System.out.println("the line readed from file-" + line + "-");
System.out.println("is the line null: "+ (line==null));
System.out.println("line length: " + line.length());
DocumentInfo documentInfo = new DocumentInfo(line);
documentsInfo.add(documentInfo);
}
br.close();
open = true;
} catch (IOException e) {
e.printStackTrace();
}
}
create the line to add:
public DocumentInfo(String fileLine) {
String delimiter = Repository.DOCUMENT_FILE_SEPARATOR;
StringTokenizer tok = new StringTokenizer(fileLine, delimiter);
System.out.println("Tokenizer starts with string: " + fileLine);
this.documentPath = tok.nextToken(); //EXCEPTION here
this.documentId = Integer.parseInt(tok.nextToken());
}
public String toString() {
String sep = Repository.DOCUMENT_FILE_SEPARATOR;
return this.getDocumentPath()+sep+this.getDocumentId()+sep+"\n";
}
I am getting the exception at the Tokenizer method (java.util.NoSuchElementException) when i try to get the nextToken, but the problem comes from the loadCollection() method. The first time i read the contents of the file nothing is there, the line is empty (lenght: 0) but the line is not null, so the while-condition fails to stop the while iteration.
Here is what i get from the debbuging prints:
the line readed from file--
is the line null: false
line length: 0
Tokenizer starts with string:
Can anyone help me with this?
You get a null only when you have exhausted the stream. But the first line of the stream (your file) is just an empty line - and you load it, the result of the empty line, is an empty string (""). It can be easily solved by skipping lines with string.length() == 0, by adding the following in your while loop:
if (line.length() == 0) continue;
You might want to consider using trim() before checking the length as well, to avoid nasty spaces making the string.length() > 0
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I guess this comes down to reading and writing to the same file. I would like to be able to return the same text file as is input, but with all integer values quadrupled. Should I even be attempting this with Java, or is it better to write to a new file and overwrite the original .txt file?
In essence, I'm trying to transform This:
12
fish
55 10 yellow 3
into this:
48
fish
220 40 yellow 12
Here's what I've got so far. Currently, it doesn't modify the .txt file.
import java.io.*;
import java.util.Scanner;
public class CharacterStretcher
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner( System.in );
System.out.println("Copy and paste the path of the file to fix");
// get which file you want to read and write
File file = new File(keyboard.next());
File file2 = new File("temp.txt");
BufferedReader reader;
BufferedWriter writer;
try {
// new a writer and point the writer to the file
FileInputStream fstream = new FileInputStream(file);
// Use DataInputStream to read binary NOT text.
reader = new BufferedReader(new InputStreamReader(fstream));
writer = new BufferedWriter(new FileWriter(file2, true));
String line = "";
String temp = "";
int var = 0;
int start = 0;
System.out.println("000");
while ((line = reader.readLine()) != null)
{
System.out.println("a");
if(line.contains("="))
{
System.out.println("b");
var = 0;
temp = line.substring(line.indexOf('='));
for(int x = 0; x < temp.length(); x++)
{
System.out.println(temp.charAt(x));
if(temp.charAt(x)>47 && temp.charAt(x)<58) //if 0<=char<=9
{
if(start==0)
start = x;
var*=10;
var+=temp.indexOf(x)-48; //converts back into single digit
}
else
{
if(start!=0)
{
temp = temp.substring(0, start) + var*4 + temp.substring(x);
//writer.write(line.substring(0, line.indexOf('=')) + temp);
//TODO: Currently writes a bunch of garbage to the end of the file, how to write in the middle?
//move x if var*4 has an extra digit
if((var<10 && var>2)
|| (var<100 && var>24)
|| (var<1000 && var>249)
|| (var<10000 && var>2499))
x++;
}
//start = 0;
}
System.out.println(temp + " " + start);
}
if(start==0)
writer.write(line);
else
writer.write(temp);
}
}
System.out.println("end");
// writer the content to the file
//writer.write("I write something to a file.");
// always remember to close the writer
writer.close();
//writer = null;
file2.renameTo(file); //TODO: Not sure if this works...
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Given that this is a pretty quick and simple hack of a formatted text file, I don't think you need to be too clever about it.
Your logic for deciding whether you are looking at a number is pretty complex and I'd say it's overkill.
I've written up a basic outline of what I'd do in this instance.
It's not very clever or impressive, but should get the job done I think.
I've left out the overwriting and reading the input form the console so you get to do some of the implementation yourself ;-)
import java.io.*;
public class CharacterStretcher {
public static void main(String[] args) {
//Assumes the input is at c:\data.txt
File inputFile = new File("c:\\data.txt");
//Assumes the output is at c:\temp.txt
File outputFile = new File("c:\\temp.txt");
try {
//Construct a file reader and writer
final FileInputStream fstream = new FileInputStream(inputFile);
final BufferedReader reader = new BufferedReader(new InputStreamReader(fstream));
final BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile, false));
//Read the file line by line...
String line;
while ((line = reader.readLine()) != null) {
//Create a StringBuilder to build our modified lines that will
//go into the output file
StringBuilder newLine = new StringBuilder();
//Split each line from the input file by spaces
String[] parts = line.split(" ");
//For each part of the input line, check if it's a number
for (String part : parts) {
try {
//If we can parse the part as an integer, we assume
//it's a number because it almost certainly is!
int number = Integer.parseInt(part);
//We add this to out new line, but multiply it by 4
newLine.append(String.valueOf(number * 4));
} catch (NumberFormatException nfEx) {
//If we couldn't parse it as an integer, we just add it
//to the new line - it's going to be a String.
newLine.append(part);
}
//Add a space between each part on the new line
newLine.append(" ");
}
//Write the new line to the output file remembering to chop the
//trailing space off the end, and remembering to add the line
//breaks
writer.append(newLine.toString().substring(0, newLine.toString().length() - 1) + "\r\n");
writer.flush();
}
//Close the file handles.
reader.close();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You may want to consider one of these:
Build the new file in memory, rather than trying to write to the same file you are reading from. You could use StringBuilder for this.
Write to a new file, then overwrite the old file with the new one. This SO Question may help you there.
With both of these, you will be able to see your whole output, separate from the input file.
Additionally, with option (2), you don't have the risk of the operation failing in the middle and giving you a messed up file.
Now, you certainly can modify the file in-place. But it seems like unnecessary complexity for your case, unless you have really huge input files.
At the very least, if you try it this way first, you can narrow down on why the more complicated version is failing.
You cannot read and simultaneously write to the same file, because this would modify the text you currently read. This means, you must first write a modified new file and later rename it to the original one. You probably need to remove the original file before renameing.
For renaming, you can use File.renameTo or see one of the many SO's questions
You seem to parse integers in your code by collecting single digits and adding them up. You should consider using either a Scanner.nextInt or employ Integer.parseInt.
You can read your file line by line, split the words at white space and then parse them and check if it is either an integer or some other word.