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.
The code is like this:
public class TxtToCsvConverter{
private static final String DATA_FILE_NAME = "/Desktop/ml-1m/movies.dat";
public static void main(String[] args) {
StringBuilder bulider = new StringBuilder();
try{
// Open the file
FileInputStream fileInputStream = new FileInputStream(DATA_FILE_NAME);
// Create a new csv file to store your data
PrintWriter writer = new PrintWriter(new File("result.csv"));
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(dataInputStream));
String strLine;
// Read file line by line
while ((strLine = reader.readLine()) != null) {
String[] stringArray = strLine.split("::");
for (int i = 0; i < stringArray.length; i++) {
bulider.append(stringArray[i]);
bulider.append(",");
}
bulider.append("\n");
}
// Close the input stream
dataInputStream.close();
// Write builder into file
writer.write(bulider.toString());
// Save the file
writer.close();
}catch (Exception e) {
// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And it appears to come out a error says
Could not find or load main class TxtToCsvConverter.data_preprocess"
I couldn't find the reason. Please help
I have a program that reads in a file using a filename specified by the user.
All file contents must be read and stored in the array. I seem to have done the IO Correctly besides this error. I understand what the error is but not sure how to correct.
EDIT: The array is already defined in the file.
Zoo.java:284: error: incompatible types: String cannot be converted to
Animals
animals[ j ] = bufferedReader.readLine();
Here is my code for the readFile Submodule:
public String readFile(Animals[] animals)
{
Scanner sc = new Scanner(System.in);
String nameOfFile, stringLine;
FileInputStream fileStream = null;
BufferedReader bufferedReader;
InputStreamReader reader;
System.out.println("Please enter the filename to be read from.");
nameOfFile = sc.nextLine();
try
{
constructed = true;
fileStream = new FileInputStream(nameOfFile);
bufferedReader = new BufferedReader(new InputStreamReader(fileStream));
while((stringLine = bufferedReader.readLine()) != null)
{
for(int j = 0; j < animals.length; j++)
{
animals[j] = bufferedReader.readLine();
}
}
fileStream.close();
}
catch(IOException e)
{
if(fileStream != null)
{
try
{
fileStream.close();
}
catch(IOException ex2)
{
}
}
System.out.println("Error in file processing: " + e.getMessage();
}
}
Thanks for the help.
animals is array of Animals, but bufferedReader.readLine() reads line. You should convert it to Animal. I don't see definition of your class Animals, but, I think, there should be constructor that takes String as argument.
So, If i'm right, you should basically write:
animals[j] = new Animals(bufferedReader.readLine());
Lots of problems in your code. Starting with the method's input. Also reading from file.
public static void main(String[] args) {
// TODO code application logic here
for(String entry : readFile())
{
System.out.println(entry);
}
}
static public String[] readFile()
{
Scanner sc = new Scanner(System.in);
InputStreamReader reader;
System.out.println("Please enter the filename to be read from.");
String nameOfFile = sc.nextLine();
try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(nameOfFile))); )
{
//constructed = true; why?
String stringLine;
ArrayList<String> arraylist = new ArrayList();
while((stringLine = bufferedReader.readLine()) != null)
{
arraylist.add(stringLine);
}
return arraylist.toArray(new String[0]);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Filetoarray.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(Filetoarray.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
I have to read data from file Here is data and want plot a graph vs thick(column 1 in data) and alpha(column 3) for every model. Every model has 7 line data,the last that start with 0 not required. Here is my code. it works but i don't think it is good code.please, suggest me better way to do the same.
public class readFile {
public static int showLines(String fileName) {
String line;
int currentLineNo = 0;
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read until endLine
while(((line = in.readLine()) != null)) {
if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
//skipping the line that start with M, # and 0.
currentLineNo++;
}
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
return currentLineNo;
}
//Now we know the dimension of matrix, so storing data into matrix
public static void readData(String fileName,int numRow) {
String line;
String temp []=null;
String data [][]=new String[numRow][10];
int i=0;
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read until endLine
while(((line = in.readLine()) != null)) {
if (!line.contains("M") && !line.contains("#") && !line.trim().startsWith("0")) {
temp=(line.trim().split("[.]"));
for (int j = 0; j<data[i].length; j++) {
data[i][j] =temp[j];
}
i++;
}
}
// Extract one column from 2d matrix
for (int j = 0; j <numRow; j=j+6) {
for (int j2=j; j2 <6+j; j2++) {
System.out.println(Double.parseDouble(data[j2][0])+"\t"+Double.parseDouble(data[j2][2]));
//6 element of every model, col1 and col3
// will add to dataset.
}
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
} finally {
try { if (in!=null) in.close(); } catch(IOException ignore) {}
}
}
//Main Method
public static void main(String[] args) {
//System.out.println(showLines("rf.txt"));
readData("rf.txt",showLines("rf.txt") );
}
}
as johnchen902 implies use a list
List<String> input=new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
input.add(line);
}
br.close();
int N=input.get(0).split(",").size(); // here add your delimiter
int M=input.size();
String[][] data=new String[M][N]
for (int i=0;i<M;i++){
String[] parts = string.split("-");
for (int k=0;k<n;k++){
data[i][k]=parts[k];
}
}
something like that
hope it helps. plz put more effort into asking the question. Give us the needed Input files, and the Code you came up with until now to solve the problem yourself.
I need to read a text file line by line using Java. I use available() method of FileInputStream to check and loop over the file. But while reading, the loop terminates after the line before the last one. i.e., if the file has 10 lines, the loop reads only the first 9 lines.
Snippet used :
while(fis.available() > 0)
{
char c = (char)fis.read();
.....
.....
}
You should not use available(). It gives no guarantees what so ever. From the API docs of available():
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
You would probably want to use something like
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null)
process(str);
in.close();
} catch (IOException e) {
}
(taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)
How about using Scanner? I think using Scanner is easier
private static void readFile(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Read more about Java IO here
If you want to read line-by-line, use a BufferedReader. It has a readLine() method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
// Do something with line
}
(Note that this code doesn't handle exceptions or close the stream, etc)
String file = "/path/to/your/file.txt";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
// Uncomment the line below if you want to skip the fist line (e.g if headers)
// line = br.readLine();
while ((line = br.readLine()) != null) {
// do something with line
}
br.close();
} catch (IOException e) {
System.out.println("ERROR: unable to read file " + file);
e.printStackTrace();
}
You can try FileUtils from org.apache.commons.io.FileUtils, try downloading jar from here
and you can use the following method:
FileUtils.readFileToString("yourFileName");
Hope it helps you..
The reason your code skipped the last line was because you put fis.available() > 0 instead of fis.available() >= 0
In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:
private List<String> loadFile() {
URI uri = null;
try {
uri = ClassLoader.getSystemResource("example.txt").toURI();
} catch (URISyntaxException e) {
LOGGER.error("Failed to load file.", e);
}
List<String> list = null;
try (Stream<String> lines = Files.lines(Paths.get(uri))) {
list = lines.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
return list;
}
//The way that I read integer numbers from a file is...
import java.util.*;
import java.io.*;
public class Practice
{
public static void main(String [] args) throws IOException
{
Scanner input = new Scanner(new File("cards.txt"));
int times = input.nextInt();
for(int i = 0; i < times; i++)
{
int numbersFromFile = input.nextInt();
System.out.println(numbersFromFile);
}
}
}
Try this just a little search in Google
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Try using java.io.BufferedReader like this.
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileName)));
String line = null;
while ((line = br.readLine()) != null){
//Process the line
}
br.close();
Yes, buffering should be used for better performance.
Use BufferedReader OR byte[] to store your temp data.
thanks.
user scanner it should work
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
public class ReadFileUsingFileInputStream {
/**
* #param args
*/
static int ch;
public static void main(String[] args) {
File file = new File("C://text.txt");
StringBuffer stringBuffer = new StringBuffer("");
try {
FileInputStream fileInputStream = new FileInputStream(file);
try {
while((ch = fileInputStream.read())!= -1){
stringBuffer.append((char)ch);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File contents :");
System.out.println(stringBuffer);
}
}
public class FilesStrings {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("input.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
while ((data = br.readLine()) != null) {
result = result.concat(data + " ");
}
System.out.println(result);
File file = new File("Path");
FileReader reader = new FileReader(file);
while((ch=reader.read())!=-1)
{
System.out.print((char)ch);
}
This worked for me
Simple code for reading file in JAVA:
import java.io.*;
class ReadData
{
public static void main(String args[])
{
FileReader fr = new FileReader(new File("<put your file path here>"));
while(true)
{
int n=fr.read();
if(n>-1)
{
char ch=(char)fr.read();
System.out.print(ch);
}
}
}
}