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();
}
}
}
}
Related
I'm just a beginner and got the following task:
Write first 100 positive and 100 negative integers to the file, listing them separated by a space.
Then read this file and put the read numbers into 2 files: positive_numbers and negative_numbers.
public static void main(String[] args) throws IOException {
File numbers = new File("C:\\numbers.txt");
File positivNumbers = new File("C:\\positivnumbers.txt");
File negativNumbers = new File("C:\\negativnumbers.txt");
try (
BufferedWriter wr = new BufferedWriter(new FileWriter(numbers));
BufferedReader rd = new BufferedReader(new FileReader(numbers));
BufferedWriter brnegativ = new BufferedWriter(new FileWriter(negativNumbers));
BufferedWriter brpositiv = new BufferedWriter(new FileWriter(positivNumbers));) {
if (numbers.exists()) {
for (int i = 0; i <= 100; i++) {
wr.write(String.valueOf((i) + " "));
}
for (int a = -1; a >= -100; a--) {
wr.write(((a) + " "));
}
String line = rd.readLine();
while (line != null) {
brpositiv.write(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I could write numbers as a String to file "numbers". But I cannot read and write them in "positiv" output file.The file is empty. Where is my mistake?
After the writing you have to close wr so all data in memory gets flushed to the file. AFTER the close you can reopen it for read. So in your code you open rd too soon.
try (BufferedWriter wr = new BufferedWriter(new FileWriter(numbers));) {
for (int i = 0; i <= 100; i++) {
wr.write(String.valueOf((i) + " "));
}
for (int a = -1; a >= -100; a--) {
wr.write(((a) + " "));
}
} catch (IOException e) {
e.printStackTrace();
}
// file is closed by try-with-resources ...
// ... so now we can open it for read:
try (BufferedReader rd = new BufferedReader(new FileReader(numbers));
BufferedWriter brnegativ = new BufferedWriter(new FileWriter(negativNumbers));
BufferedWriter brpositiv = new BufferedWriter(new FileWriter(positivNumbers));) {
String line = rd.readLine();
while (line != null) {
brpositiv.write(line);
// TODO : split logic
}
} catch (IOException e) {
e.printStackTrace();
}
I have 3 text files. Numbers.txt have int and double values like 1 1.5 2... I wanna put my int values to my Int.txt and double values to Double.txt.
So how can I do?
I tried .hasNextDouble() or .hasNextInt()
public static void main(String[] args) {
File f = new File("a.rtf");
File fWrite = new File("aWrite");
try {
FileReader fr = new FileReader(f);
FileWriter fw = new FileWriter(fWrite);
double c = fr.read();
while(c != -1){
char k = (char)c;
c.hasNextDouble();
System.out.print(k + " ");
fw.write((int) c);
c = fr.read();
}
fr.close();
fw.close();
} catch(Exception e) {
e.printStackTrace();
}
I am new in Java. What else can I try?
You can try this:
Writer wr = new FileWriter("aWrite.txt");
wr.write(String.valueOf(1));
wr.write(String.valueOf(1.5));
wr.write(String.valueOf(2));
wr.flush();
wr.close();
Or this approach which is mainly better for bigger data:
File file = new File("aWrite.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("Write the string to text file");
out.newLine();
I find another way. I hope help...
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args)throws IOException {
double[] doubleNumbers = new double[6];
int[] integerNumbers = new int[6];
int intCount = 0;
int doubleCount = 0;
File numbers = new File("numbers.txt");
FileReader fr = new FileReader(numbers);
LineNumberReader lnreader= new LineNumberReader(fr);
String line = "";
while ((line = lnreader.readLine()) != null) {
var _temp = line.split(" ");
for(int i = 0;i<_temp.length;i++) {
if(_temp[i].indexOf(".") > 0) {
doubleNumbers[doubleCount] = Double.parseDouble(_temp[i]);
++doubleCount;
}else {
integerNumbers[intCount] = Integer.parseInt(_temp[i]);
++intCount;
}
}
}
fr.close();
File doubleFile = new File("double.txt");
FileWriter fw = new FileWriter(doubleFile);
for(int i = 0;i<doubleCount;i++) {
fw.write(doubleNumbers[i]+" ");
if((i +1) % 3 == 0)
fw.write("\n");
}
fw.flush();
fw.close();
File integerFile = new File("integer.txt");
FileWriter fw = new FileWriter(integerFile);
for(int i = 0;i<intCount;i++) {
fw.write(integerNumbers[i]+" ");
if((i +1) % 3 == 0)
fw.write("\n");
}
fw.flush();
fw.close();
System.out.print("Done");
}
}
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.
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
I am trying to add almost 2lac lines in particular txt file(actually conf file) by java program. But it takes almost 112 min when number is only 189000!
I write following code for that
import java.io.*;
public class Fileshandling_example {
static long s1;
static long e1;
static long e2;
static Fileshandling_example fhe= new Fileshandling_example();
public static void main(String args[]) {
try {
s1 = System.nanoTime();
File file1 = new File("\example\mandar.txt");
LineNumberReader lnr1 = new LineNumberReader(new FileReader(file1));
BufferedReader br1 = new BufferedReader(new FileReader(file1));
lnr1.skip(Long.MAX_VALUE);
int a = 1;
StringBuffer sb1 = new StringBuffer("[stations]");
String sCurrentline1 = br1.readLine();
while ((sCurrentline1 = br1.readLine()) != null) {
a++;
if (sCurrentline1.contentEquals(sb1) == true) {
int count = a;
int arraycount = 100000;
for(int i =0; i< (arraycount+1); i++){
if(0 == (i%10000)){
e2 = System.nanoTime();
System.out.println("Time = "+(e2-s1));
}
String abc ="extern => 00"+(1000 + (arraycount-i))+",1,Wait(0.05)";
fhe.insertintoExtensions(file1, (count+1),abc);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
e1 = System.nanoTime();
System.out.println("Time = "+(e1-s1));
}
public void insertintoExtensions(File inFile1, int lineno, String s1)throws Exception {
File outFile1 = new File("\example\111.tmp");
FileInputStream fis = new FileInputStream(inFile1);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fos = new FileOutputStream(outFile1);
PrintWriter out = new PrintWriter(fos);
String thisLine = "";
int i =1;
while ((thisLine = in.readLine()) != null) {
if(i == lineno) out.println(s1);
out.println(thisLine);
i++;
}
out.flush();
out.close();
in.close();
inFile1.delete();
outFile1.renameTo(inFile1);
}
}
Can any one help me where i get wrong?
I asked similar question coderanch but here i get clue very fast so i ask here also.
Sorry for that (cross forum asking).
Thanks.
You are loop 100,000 times for every '[stations]' found on "\example\mandar.txt":
if (sCurrentline1.contentEquals(sb1) == true) {
int count = a;
int arraycount = 100000;
for(int i =0; i< (arraycount+1); i++){
and call fhe.insertintoExtensions which loops "\example\mandar.txt" again to copy or the content of the line or the content of s1 parameter until the actual line number is reached:
while ((thisLine = in.readLine()) != null) {
if(i == lineno) out.println(s1);
out.println(thisLine);
i++;
}
Try to improve you code and use BufferedWriter instead of PrintWriter.