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.
My target is i have one txt file it contains some line of text. in this i have two words i.e A and 1. if line has "A" letter then next lines goto one file until next line contain "1" and if line contain "1" then next lines goto other file until "A" find.
Input file like follows
A
rahu
pahdu
jhaani
1
hjsdh
dhj
A
jiko
raju
A
tenk
kouou
I am expecting output
A.txt contain
rahu
pahdu
jhaani
Same
1.txt
My code
{
fis = new FileInputStream("E:\\Input.txt");
reader = new BufferedReader(new InputStreamReader(fis));
System.out.println("Reading File line by line using BufferedReader");
String line = reader.readLine();
while(line != null){
if(line.contains("LETTER00~VSAQCCCC~H~")) {
line = reader.readLine();
System.out.println(line);
}
else {
line= reader.readLine();
}
}
}
You could just repoint your FileOutputStream whenever you find a 1 or A.
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("in.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fosA = new FileOutputStream("out_A.txt");
FileOutputStream fos1 = new FileOutputStream("out_1.txt");
FileOutputStream fos = null;
System.out.println("Reading File line by line using BufferedReader");
String line = reader.readLine();
while (line != null) {
System.out.println(line);
if(line.equals("A"))
{
fos = fosA;
line = reader.readLine();
continue;
}
if(line.equals("1"))
{
fos = fos1;
line = reader.readLine();
continue;
}
fos.write(line.getBytes());
fos.write('\n');
fos.flush();
line = reader.readLine();
}
fos.close();
fosA.close();
fos1.close();
}
You can do something like this.
System.out.println("Reading File line by line using
BufferedReader");
String inputFIle = "";
String line;
boolean flag = false;
// String line = reader.readLine();
while ((line = reader.readLine()) != null) {
if (line.trim().equalsIgnoreCase("A")) {
inputFIle = "A.txt";
} else if(line.trim().equalsIgnoreCase("1")){
inputFIle = "1.txt";
}
else{
write(line, inputFIle);
}
}
You can do something like this
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new FileReader("Input.txt"));
boolean isFound = false;
List<String> main_list = new ArrayList<>();
List<String> sub_list = new ArrayList<>();
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(line.contains("A")) {
isFound = true;
} else if(line.contains("1")) {
isFound = false;
for (String aSub_list : sub_list) {
main_list.add(aSub_list);
}
sub_list.clear();
}
if(isFound && !line.contains("A")) {
sub_list.add(line);
}
}
for (String aMain_list : main_list) {
System.out.println(aMain_list);
}
}
I want to calculate some column data and write it to csv file as column. Then after calculating other column of data I want to append it to same file but as new column.
Here is what I did:
try {
FileWriter writer = new FileWriter(OUT_FILE_PATH, true);
for (int i=0; i<data.size(); i++) {
writer.append(String.valueOf(data.get(i)));
writer.append(",");
writer.append("\n");
}
writer.flush();
writer.close();
} catch (Exception e) {}
Result - It appends the new column below the first column, so I have single long column.
Thanks,
Something like this perhaps:
public void appendCol(String fileName, ???ArrayList??? data) { //assuming data is of type ArrayList here, you need to be more explicit when posting code
String lineSep = System.getProperty("line.separator");
String output = "";
try{
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
int i = 0;
while ((line = br.readLine()) != null) {
output += line.replace(
lineSep,
"," + String.valueOf(data.get(i)) + lineSep);
i++;
}
br.close();
FileWriter fw = new FileWriter(fileName, false); //false to replace file contents, your code has true for append to file contents
fw.write(output);
fw.flush();
fw.close();
} catch (Exception e){
e.printStackTrace();
}
}
You will have to read your file (line by line) and then insert the new column to every line. Here's a solution using BufferedReader and BufferedWriter
public void addColumn(String path,String fileName) throws IOException{
BufferedReader br=null;
BufferedWriter bw=null;
final String lineSep=System.getProperty("line.separator");
try {
File file = new File(path, fileName);
File file2 = new File(path, fileName+".1");//so the
//names don't conflict or just use different folders
br = new BufferedReader(new InputStreamReader(new FileInputStream(file))) ;
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2)));
String line = null;
int i=0;
for ( line = br.readLine(); line != null; line = br.readLine(),i++)
{
String addedColumn = String.valueOf(data.get(i));
bw.write(line+addedColumn+lineSep);
}
}catch(Exception e){
System.out.println(e);
}finally {
if(br!=null)
br.close();
if(bw!=null)
bw.close();
}
}
I have used apache-commons for resolving this issue. There was no perfect answer that worked for me. After a lot of effort, this worked for me.
Writer writer = Files.newBufferedWriter(Paths.get("output.csv"));
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
//add whichever column you want in withHeader
.withHeader("createdTs", "destroyedTs", "channelName", "uid", "suid", "did", "joinTs", "leaveTs", "platform", "location", "consumption"));
//actual columns in your passed CSV
String[] HEADERS = {"createdTs", "destroyedTs", "channelName", "uid", "suid", "did", "joinTs", "leaveTs", "platform", "location"};
Reader in = new FileReader(yourCsvFile);
Iterable<CSVRecord> records = CSVFormat.DEFAULT
.withHeader(HEADERS)
.withFirstRecordAsHeader()
.parse(in);
for (CSVRecord row : records) {
String tempValue = String.valueOf(Long.parseLong(row.get("leaveTs")) - Long.parseLong(row.get("joinTs")));
csvPrinter.printRecord(row.get("createdTs"), row.get("destroyedTs"),row.get("channelName"), row.get("uid"),
row.get("suid"), row.get("did"), row.get("joinTs"), row.get("leaveTs"),
row.get("platform"), row.get("location"), tempValue);
}
Hope this will help you.
{
//CREATE CSV FILE
StringBuffer csvReport = new StringBuffer();
csvReport.append("header1,Header2,Header3\n");
csvReport.append(value1 + "," + value2 + "," + value3 + "\n");
generateCSVFile( filepath,fileName, csvReport); // Call the implemented mathod
}
public void generateCSVFile(String filepath,String fileName,StringBuffer result)
{
try{
FileOutputStream fop = new FileOutputStream(filepath);
// get the content in bytes
byte[] contentInBytes = result.toString().getBytes();
fop.write(contentInBytes);
fop.flush();
//wb.write(fileOut);
if(fop != null)
fop.close();
}catch (Exception ex)
{
ex.printStackTrace();
}
}
private static void readFile1(String in, String out) throws IOException
{
FileInputStream fis = new FileInputStream(new File(in));
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter writer = null;
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(out), "utf-8"));
String line = null;
while ((line = br.readLine()) != null)
{
if(line.length() > 0)
{
String[] words = line.split("\\s+");
for(String word : words)
{
if(word.charAt(0)=='*')
{
//System.out.println(word);
writer.write(word);
writer.newLine();
}
}
}
}
br.close();
writer.close();
fis.close();
}
}
Can someone help me with this one?
In cmd i get something like "Exception in thread "main" java.lang.StringIndexOutOfBoundsException:String index out of range:0
The only place you seem to be referencing an index on a string is this if-statement:
if(word.charAt(0)=='*')
Change your if statement to be:
if(!word.isEmpty() && word.charAt(0)=='*')
This will first check if the word is empty and if it is not, then it will look for the proper char
UPDATE
You should add in a NULL check on word as well, just to avoid a NullPointerException
if(word != null && !word.isEmpty() && word.charAt(0)=='*')
Can anyone point me in the right direction here. I have a method that is supposed to read a file and display the data in that file. I can only get it to display one line. I know it is something simple I am over looking, but my brain is mush and I just keep digging a bigger hole.
public static String readFile(String file) {
String data = "";
if (!new java.io.File(file).exists()) {
return data;
}
File f = new File(file);
FileInputStream fStream = null;
BufferedInputStream bStream = null;
BufferedReader bReader = null;
StringBuffer buff = new StringBuffer();
try {
fStream = new FileInputStream(f);
bStream = new BufferedInputStream(fStream);
bReader = new BufferedReader(new InputStreamReader(bStream));
String line = "";
while (bStream.available() != 0) {
line = bReader.readLine();
if (line.length() > 0) {
if (line.contains("<br/>")) {
line = line.replaceAll("<br/>", " ");
String tempLine = "";
while ((tempLine.trim().length() < 1)
&& bStream.available() != 0) {
tempLine = bReader.readLine();
}
line = line + tempLine;
}
buff.append(line + "\n");
}
}
fStream.close();
bStream.close();
bReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buff.toString();
}
String line = null;
while ((line = bReader.readLine())!=null)
How about doing this with Guava:
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html
List<String> lines = Files.readLines("myFile.txt", Charset.forName("UTF-8"));
System.out.println(lines);
You'd still have to do a little bit of work to concatenate the <br> lines etc...