Reading twice an InputStream throws IOException - java

I'm facing a problem, can someone tell me how to void this? It throws up an "java.io.IOException: Stream closed". I know where my mistake is but I dont know how to fix it. BufferedReader closes from the first function and I dont know how to reset it within the second one. Function should format text from one text file to another with tabs. Thank you
import java.io.*;
public class TestClass {
private void prosekStudentKRS(FileReader fr) throws IOException{
BufferedReader reader = null;
int j = 0, vksum = 0;
try{
reader = new BufferedReader(fr);
reader.readLine();
String line;
while((line = reader.readLine()) != null) {
int sum = 0;
j++;
String[] niza = line.split(",");
for(int i = 1; i < niza.length; i ++) {
sum+=Integer.parseInt(niza[i]);
}
vksum += Integer.parseInt(niza[1]);
System.out.printf("Student %d ima prosek %.2f\n", j, (float) sum / 3);
}
System.out.println("Prosek po KRS: " + vksum / (double) j);
} catch (Exception e){
e.printStackTrace();
} finally {
if(reader != null) {
reader.close();
}
}
}
private void TSV(FileReader fr, FileWriter fw) throws IOException {
BufferedReader reader = null;
BufferedWriter writer = null;
StringBuilder sb = null;
try {
reader = new BufferedReader(fr);
writer = new BufferedWriter(fw);
String line;
while ((line = reader.readLine()) != null) {
String[] niza = line.split(",");
sb = new StringBuilder();
for(int i = 0; i < niza.length; i ++) {
sb.append(niza[i] + "\t");
}
writer.write(sb.toString());
writer.newLine();
writer.flush();
}
} finally {
if (reader != null)
reader.close();
if(writer != null) {
writer.flush();
writer.close();
}
}
}
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("C:\\Users\\pc\\IdeaProjects\\LabOS01\\rezultaticsv.txt");
FileWriter fw = new FileWriter("C:\\Users\\pc\\IdeaProjects\\LabOS01\\rezultatitsv.txt");
TestClass filetest = new TestClass();
filetest.prosekStudentKRS(fr);
filetest.TSV(fr, fw);
}
}

Either create two distinct FileReader objects and pass a different to each method.
Otherwise you can also create a BufferedReader from the FileReader before invoking the methods, pass it to the first method, reset it with the reset() method and pass it to the other method.
As alternative if the file is not too big, you could store in a List<String> each line read rather than reading again the file.
It would be more efficient.

Related

Not able to write on a file

The above is a working code snippet. The code runs fine but it does not write what is inside the else if(line.contains("{NEW_LIMIT}")) statement.
Another problem is that after the program writes into a new text file it loses its original format, as in to say it just writes everything in a single line.
Is there anything I am doing wrong?
public static void replace1(String name, String limit, String nlimit) throws IOException
{
File infile = new File("s://BlackBuck/Question_1_Template.txt");
File outfile = fileReturn();
FileWriter fw;
BufferedWriter bw = null;
FileReader fr;
BufferedReader br = null;
String line, putdata = null;;
try {
fr = new FileReader(infile);
br = new BufferedReader(fr);
fw = new FileWriter(outfile);
bw = new BufferedWriter(fw);
while((line = br.readLine()) != null)
{
if(line != null)
{
if(line.contains("{CUSTOMER_NAME}"))
{
putdata = line.replace("{CUSTOMER_NAME}", name);
bw.write(putdata);
}
else if(line.contains("{CURRENT_LIMIT}"))
{
putdata = line.replace("{CURRENT_LIMIT}", limit);
bw.write(putdata);
}
else if(line.contains("{NEW_LIMIT}"))
{
putdata = line.replace("{NEW_LIMIT}", nlimit);
bw.write(putdata);
}
else
{
bw.write(line);
}
}
}
}finally {
bw.close();
br.close();
}
}
If a line contains {CUSTOMER_NAME} or {CURRENT_LIMIT}, then statements {NEW_LIMIT} won't be run. You can simply fix this using following codes:
if(line != null) {
putdata = line.replace("{CUSTOMER_NAME}", name)
.replace("{CURRENT_LIMIT}", limit)
.replace("{NEW_LIMIT}", nlimit);
bw.write(putdata);
// append a line separator to current line
bw.newLine();
}

Write to file in Java – BufferedWriter

I created a class (LerEscreverArquivo) that reads the contents of a text file, does a treatment on the read data, prints on the screen the result of the treatment done and writes in a text file the information.
The data reading and writing on the screen is working. The problem happens at the time of writing the values ​​in the text file.
The script only writes the last record it writes to the file. The previous records it ignores. It follows the code and the images of the problem.
public class LerEscreverArquivo {
private static final String NomeArquivoEntrada = "E:\\DesafioProgramacao\\matriculasSemDV.txt";
private static final String NomeArquivoSaida = "E:\\DesafioProgramacao\\matriculasComDV.txt";
public static void main(String[] args) {
FileReader fr = null;
BufferedReader br = null;
BufferedWriter bw = null;
FileWriter fw = null;
try {
//input file
fr = new FileReader(NomeArquivoEntrada);
br = new BufferedReader(fr);
String sCurrentLine;
System.out.println("Início do arquivo.");
while ((sCurrentLine = br.readLine()) != null) {
if (!sCurrentLine.isEmpty()) {
int Total = 0;
int contador = 5;
int resto;
for (int i = 0; i < sCurrentLine.length(); i++) {
int j = Character.digit(sCurrentLine.charAt(i), 10);
Total = Total + (j * contador);
contador = contador - 1;
}
resto = Total / 16;
String decimal = Integer.toHexString(resto);
String DigitoCod=sCurrentLine + "-" + decimal;
//output file
fw = new FileWriter(NomeArquivoSaida);
bw = new BufferedWriter(fw);
bw.write(DigitoCod);
System.out.println(DigitoCod);
}
}
System.out.println("Fim do arquivo.");
} catch (IOException eReader) {
eReader.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (fr != null) {
fr.close();
}
if(bw != null) {
bw.close();
}
if(fw != null) {
fw.close();
}
} catch (IOException exeReader) {
exeReader.printStackTrace();
}
}
}
}
You are initializing the FileWriter in each iteration of the loop
fw = new FileWriter(NomeArquivoSaida);
bw = new BufferedWriter(fw);
bw.write(DigitoCod);
So basically your file is started fresh by removing the previous contents.
Try moving the following two lines above the loop and your problem should be solved.
fw = new FileWriter(NomeArquivoSaida);
bw = new BufferedWriter(fw);
EDIT
Working code is following:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class LerEscreverArquivo{
private static final String NomeArquivoEntrada = "matriculasSemDV.txt";
private static final String NomeArquivoSaida = "matriculasComDV.txt";
public static void main(String[] args) {
FileReader fr = null;
BufferedReader br = null;
BufferedWriter bw = null;
FileWriter fw = null;
try {
// input file
fr = new FileReader(NomeArquivoEntrada);
br = new BufferedReader(fr);
fw = new FileWriter(NomeArquivoSaida);
bw = new BufferedWriter(fw);
String sCurrentLine = "";
System.out.println("Início do arquivo.");
while ((sCurrentLine = br.readLine()) != null) {
if (!sCurrentLine.isEmpty()) {
int Total = 0;
int contador = 5;
int resto;
for (int i = 0; i < sCurrentLine.length(); i++) {
int j = Character.digit(sCurrentLine.charAt(i), 10);
Total = Total + (j * contador);
contador = contador - 1;
}
resto = Total / 16;
String decimal = Integer.toHexString(resto);
String DigitoCod = sCurrentLine + "-" + decimal;
// output file
bw.write(DigitoCod);
System.out.println(DigitoCod);
}
}
System.out.println("Fim do arquivo.");
} catch (IOException eReader) {
eReader.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (fr != null) {
fr.close();
}
if (bw != null) {
bw.close();
}
if (fw != null) {
fw.close();
}
} catch (IOException exeReader) {
exeReader.printStackTrace();
}
}
}
}

How to input the data from multiple csv files using java

I have some CSV file with the same column header.
I want to make them to one file.So I found something similar to me. Link is Merge CSV files into a single file with no repeated headers.
but I want to return the data as a String, but this code has no return.
I try to modify that. but I failed.
I want to put the data from several csv into one variable.
String[] headers = null;
String firstFile = "/path/to/firstFile.dat";
Scanner scanner = new Scanner(new File(firstFile));
if (scanner.hasNextLine())
headers[] = scanner.nextLine().split(",");
scanner.close();
Iterator<File> iterFiles = listOfFilesToBeMerged.iterator();
BufferedWriter writer = new BufferedWriter(new FileWriter(firstFile, true));
while (iterFiles.hasNext()) {
File nextFile = iterFiles.next();
BufferedReader reader = new BufferedReader(new FileReader(nextFile));
String line = null;
String[] firstLine = null;
if ((line = reader.readLine()) != null)
firstLine = line.split(",");
if (!Arrays.equals (headers, firstLine))
throw new FileMergeException("Header mis-match between CSV files: '" +
firstFile + "' and '" + nextFile.getAbsolutePath());
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
reader.close();
}
writer.close();
Here is what you might be looking for.
I have read two csv files and written into one.
Hope this is use full...
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class CombineTwoFile
{
public static void main(String[] args) throws IOException
{
ArrayList<String> list = new ArrayList<String>();
try
{
BufferedReader br = new BufferedReader(new FileReader( "d:\\1\\1.csv"));
BufferedReader r = new BufferedReader(new FileReader( "d:\\1\\2.csv"));
String s1 =null;
String s2 = null;
while ((s1 = br.readLine()) != null)
{
list.add(s1);
}
while((s2 = r.readLine()) != null)
{
list.add(s2);
}
}
catch (IOException e)
{
e.printStackTrace();
}
BufferedWriter writer=null;
writer = new BufferedWriter(new FileWriter("d:\\1\\good.csv"));
String listWord;
for (int i = 0; i< list.size(); i++)
{
listWord = list.get(i);
writer.write(listWord);
writer.write("\n");
}
System.out.println("DONE Enjoy!!");
writer.close();
}
}
Or if you looking for a function which returns String combining two csv
public static String combineCSV() {
ArrayList<String> list = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(
"d:\\1\\1.csv"));
BufferedReader r = new BufferedReader(
new FileReader("d:\\1\\2.csv"));
String s1 = null;
String s2 = null;
while ((s1 = br.readLine()) != null) {
list.add(s1);
}
while ((s2 = r.readLine()) != null) {
list.add(s2);
}
} catch (IOException e) {
e.printStackTrace();
}
String listWord;
StringBuffer objBuffer = new StringBuffer();
for (int i = 0; i < list.size(); i++) {
listWord = list.get(i);
objBuffer.append(listWord);
objBuffer.append("\n");
}
System.out.println("DONE Enjoy!!");
System.out.println(objBuffer);
return objBuffer.toString();
}
Thank you!!!!
Enjoy Coding...
Another alternative is to use Open CSV library

writing and reading a file of strings

Hi friends this is my program to create(write) an array of integer file and reading it..and it is working..now i want to create a file of Strings.Can someone help me please?
public class File {
public static void main(String args[]) throws IOException{
int[] array={010100101,0010010};
OutputStream os=new FileOutputStream("arun");
for(int i=0;i<array.length;i++){
os.write(array[i]);
}
InputStream is=new FileInputStream("arun");
for(int i=0;i<array.length;i++){
System.out.println(is.read());
}
}
}
Just use the ByteArray of the String.
String[] array = { "010100101", "0010010" };
try {
// write
OutputStream os = new FileOutputStream("arun");
for (int i = 0; i < array.length; i++) {
os.write(array[i].getBytes(Charset.forName("UTF-8")));
}
// read
InputStream is = new FileInputStream("arun");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while (( line = reader.readLine() ) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("You fucked up!");
}

Java Text Input: How to ignore lines starting with certain characters in them?

I basically want to ignore certain lines with characters in them, like if there's a line
// hello, i'm bill
I want to ignore that line while reading it because it contains the character "//". How can I do that? I tried method skip(), but it gives me errors.
public String[] OpenFile() throws IOException {
FileReader reader = new FileReader(path);
BufferedReader textReader = new BufferedReader(reader);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for (i=0; i<numberOfLines; i++) {
textData[i] = textReader.readLine();
}
// close the line-by-line reader and return the data
textReader.close();
return textData;
}
int readLines() throws IOException {
FileReader reader = new FileReader(path);
BufferedReader textReader = new BufferedReader(reader);
String line;
int numberOfLines = 0;
while ((line = textReader.readLine()) != null) {
// I tried this:
if (line.contains("//")) {
line.skip();
}
numberOfLines++;
}
reader.close();
return numberOfLines;
}
Update: HERE's MY MAIN METHOD:
try{
ReadFile files = new ReadFile(file.getPath());
String[] anyLines = files.OpenFile();
}
while ((line = textReader.readLine()) != null) {
// I tried this:
if (line.contains("//")) {
continue;
}
numberOfLines++;
}
note that continue might seem a bit goto like and be prone to critique
edit here's what you are after (note this doesn't need the countLines method)
public String[] OpenFile() throws IOException {
FileReader reader = new FileReader(path);
BufferedReader textReader = new BufferedReader(reader);
List<String> textData = new LinkedList<String>();//linked list to avoid realloc
String line;
while ((line = textReader.readLine()) != null) {
if (!line.contains("//")) textData.add(line);
}
// close the line-by-line reader and return the data
textReader.close();
return textData.toArray(new String[textData.size()]);
}
As Andrew Thompson points out, it would be best to read the file line by line into an ArrayList. Pseudo-Code:
For Each Line In File
If LineIsValid()
AddLineToArrayList()
Next
UPDATE to fix your actual code:
public String[] OpenFile() throws IOException {
FileReader reader = new FileReader(path);
BufferedReader textReader = new BufferedReader(reader);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int BufferIndex = 0;
String line;
while ((line = textReader.readLine()) != null) {
if (line.trim().startsWith("//")) {
// Don't inject current line into buffer
}else{
textData[BufferIndex] = textReader.readLine();
BufferIndex = BufferIndex + 1;
}
}
// close the line-by-line reader and return the data
textReader.close();
return textData;
}
In your ReadLines() Function:
while ((line = textReader.readLine()) != null) {
if (line.trim().startsWith("//")) {
// do nothing
}else{
numberOfLines++;
}
}
Basically, you're on the right track.
Note: You may be interested in the startsWith() string function

Categories