this is the code that i have found in the internet for reading the lines of a file and also I use eclipse and I passed the name of files as SanShin.txt in its argument field. but it will print :
Error: textfile.txt (The system cannot find the file specified)
Code:
public class Zip {
public static void main(String[] args){
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
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());
}
}
}
please help me why it prints this error.
thanks
...
// command line parameter
if(argv.length != 1) {
System.err.println("Invalid command line, exactly one argument required");
System.exit(1);
}
try {
FileInputStream fstream = new FileInputStream(argv[0]);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get the object of DataInputStream
...
> java -cp ... Zip \path\to\test.file
When you just specify "textfile.txt" the operating system will look in the program's working directory for that file.
You can specify the absolute path to the file with something like new FileInputStream("C:\\full\\path\\to\\file.txt")
Also if you want to know the directory your program is running in, try this:
System.out.println(new File(".").getAbsolutePath())
Your new FileInputStream("textfile.txt") is correct. If it's throwing that exception, there is no textfile.txt in the current directory when you run the program. Are you sure the file's name isn't actually testfile.txt (note the s, not x, in the third position).
Off-topic: But your earlier deleted question asked how to read a file line by line (I didn't think you needed to delete it, FWIW). On the assumption you're still a beginner and getting the hang of things, a pointer: You probably don't want to be using FileInputStream, which is for binary files, but instead use the Reader set of interfaces/classes in java.io (including FileReader). Also, whenever possible, declare your variables using the interface, even when initializing them to a specific class, so for instance, Reader r = new FileReader("textfile.txt") (rather than FileReader r = ...).
Related
Goal of this assignment is to create a while loop that goes through file "flowers.dat" (I'll paste it later in this post) until the EoF is reached, then it should print a flowers name and if it'll grow in the shade or sun. Here's what I've got so far:
import java.io.*; // Import class for file input.
public class Flowers
{
public static void main(String args[]) throws Exception
{
// Declare variables here
String flowerName;
String sunOrShade;
File flower = new File("flowers.dat");
// Open input file.
// Create BufferedReader object.
BufferedReader reader;
// Write while loop that reads records from file.
while ((flowerName = reader.readLine()) != null) {
System.out.println(flowerName + "is grown in the " + sunOrShade);
}
// Print flower name and the words sun or shade.
flower.close();
System.exit(0);
} // End of main() method.
}
Here is the "flowers.dat". Here I noted that the Flower and sun/shade alternate, so it makes me think that I need to include a for loop in the while loop that alternates between each line, assigns one line to flowerName and the other to sunOrShade, then prints the line and it again until it reaches null.
Astilbe
Shade
Marigold
Sun
Begonia
Sun
Primrose
Shade
Cosmos
Sun
Dahlia
Sun
Geranium
Sun
Foxglove
Shade
Trillium
Shade
Pansy
Sun
Petunia
Sun
Daisy
Sun
Aster
Sun
Also, I'm getting this error message. I'm not sure why it doesn't close the .dat file
Flowers.java30: error : cannot find symbol
flower.close();
^
symbol: method close()
location: variable flower of type File
Error: could not find or load main class Flowers
The class File is just for the classpath, it is not about opening any stream. Not valid to call method close on the flower instance which is a File object.
flower is declared as a File object and there is no close() method for this object. You need to initialize your BufferedReader (reader)
BufferedReader reader = new BufferedReader(new FileReader(flower));
and close that since that is what will be accessing the file and reading it. It should be reader.close(). That should solve the particular error you mentioned. But take it a littler further so that you don't need close the reader and allow it to close itself when things are done or an Exception occurs by using Try With Resources when setting up the reader:
File flower = new File("flowers.dat");
try (BufferedReader reader = new BufferedReader(new FileReader(flower))) {
// Write while loop that reads records from file.
while ((flowerName = reader.readLine()) != null) {
//read in the next line to get the required lighting.
sunOrShade = reader.readLine();
System.out.println(flowerName + " is grown in the " + sunOrShade);
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
And you don't need System.exit(0); to end the application. It will end when the main() method is finished.
I am writing code to process a list of tar.gz files, inside which there are multiple, csv files. I have encountered the error below
com.opencsv.exceptions.CsvMalformedLineException: Unterminated quoted field at end of CSV line. Beginning of lost text: [,,,,,,
]
at com.opencsv.CSVReader.primeNextRecord(CSVReader.java:245)
at com.opencsv.CSVReader.flexibleRead(CSVReader.java:598)
at com.opencsv.CSVReader.readNext(CSVReader.java:204)
at uk.ac.shef.inf.analysis.Test.readAllLines(Test.java:64)
at uk.ac.shef.inf.analysis.Test.main(Test.java:42)
And the code causing this problem is below, on line B.
public class Test {
public static void main(String[] args) {
try {
Path source = Paths.get("/home/xxxx/Work/data/amazon/labelled/small/Books_5.json.1.tar.gz");
InputStream fi = Files.newInputStream(source);
BufferedInputStream bi = new BufferedInputStream(fi);
GzipCompressorInputStream gzi = new GzipCompressorInputStream(bi);
TarArchiveInputStream ti = new TarArchiveInputStream(gzi);
CSVParser parser = new CSVParserBuilder().withStrictQuotes(true)
.withQuoteChar('"').withSeparator(',').
.withEscapeChar('|'). // Line A
build();
BufferedReader br = null;
ArchiveEntry entry;
entry = ti.getNextEntry();
while (entry != null) {
br = new BufferedReader(new InputStreamReader(ti)); // Read directly from tarInput
System.out.format("\n%s\t\t > %s", new Date(), entry.getName());
try{
CSVReader reader = new CSVReaderBuilder(br).withCSVParser(parser)
.build();
List<String[]> r = readAllLines(reader);
} catch (Exception ioe){
ioe.printStackTrace();
}
System.out.println(entry.getName());
entry=ti.getNextEntry(); // Line B
}
}catch (Exception e){
e.printStackTrace();
}
}
private static List<String[]> readAllLines(CSVReader reader) {
List<String[]> out = new ArrayList<>();
int line=0;
try{
String[] lineInArray = reader.readNext();
while(lineInArray!=null) {
//System.out.println(Arrays.asList(lineInArray));
out.add(lineInArray);
line++;
lineInArray=reader.readNext();
}
}catch (Exception e){
System.out.println(line);
e.printStackTrace();
}
System.out.println(out.size());
return out;
}
}
I also attach a screenshot of the actual line within the csv file that caused this problem here, look at line 5213. I also include a test tar.gz file here: https://drive.google.com/file/d/1qHfWiJItnE19-BFdbQ3s3Gek__VkoUqk/view?usp=sharing
While debugging, I have some questions.
I think the issue is the \ character in the data file (line 5213 above), which is the escape character in Java. I verified this idea by adding line A to my code above, and it works. However, obviously I don't want to hardcode this as there can be other characters in the data causing same issue. So my question 1 is: is there anyway to tell Java to ignore escape characters? Something like the opposite of withEscapeChar('|')? UPDATE: the answer is to use '\0', thanks to the first comment below.
When debugging, I notice that my program stops working on the next .csv file within the tar.gz file as soon as it hit the above exception. To explain what I mean, inside the tar.gz file included in the above link, there are two csvs: _10.csv and _110.csv. The problematic line is in _10.csv. When my program hit that line, an exception is thrown and the program moves on to the next file _110.csv (entry=ti.getNextEntry();). This file is actually fine, but the method readAllLines that is supposed to read this next csv file will throw the same exception immediately on the first line. I don't think my code is correct, especially the while loop: I suspect the input stream was still stuck at the previous position that caused the exception. But I don't know how to fix this. Help please?
using RFC4180Parser worked for me.
i have problem which is probably easy but in can't figure it out. I'm writing simple java program called task1 to read a file and calculate some values. I run this program in cmd like this:
cmd: java task1 calculate
Word "calculate" after "task1" is an argument which start my method to calculate some values. But i would like to calculate some values in a file called values.txt. My problem is that i don't know how to write my code to that read file. This file is passed as argument in cmd like that:
cmd: java task1 calculate < values.txt
hope, you can understand my problem. It Would be awesome if you can just tell me how to print this values in my file
if(args.length == 0)
{
System.out.println("Insert some arguments");
}
else if(args[0].equals("calculate"))
{
//here i would like to read my file (values.txt)
}
I appreciate your help and i am sorry for my bad English.
You should use buffered reader for that.
When you do
cmd: java task1 calculate < values.txt
you pass the contents of values.txt in the program as standard input.
The code would look like this
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String line = bufferedReader.readLine();
This way you read a line with BufferedReader.
For more please consult http://alvinalexander.com/java/java-bufferedreader-readline-string-examples
PS: It is also possible to directly read a file from disk, no need to pipe it to the program.
You do that like this:
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
You can try Files#readAllLines(). This will read a text file and store every line in
a List collection:
//Path valuesPath = Paths.get("VALUES_DIR", "values.txt");
Path valuesPath = Paths.get("./" + args[0]);
try {
List<String> lines = Files.readAllLines(valuesPath, Charset.defaultCharset()));
for (String line : lines) { //print lines (or do whatever you need)
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Where args[0] is the name of the file to read (on the same directory where the task1.jar is).
Call your java program as:
java -jar task1.jar values.txt
EDIT:
To read piped file as standard in:
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) { //print lines (or do whatever you need)
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
call your task as:
java task1 calculate < VALUES_PATH\values.txt
Where VALUES_PATH is the complete path where your file is.
Note that when you use < then you can't get back the command line in your own program.
I'm trying to write a program that reads a file (which is a Java source file), makes an Arraylist of certain specified values from that file. and outputs that Arraylist into another resulting file.
I'm using PrintWriter to make the new resulting file. This is a summarised version of my program:
ArrayList<String> exampleArrayList = new ArrayList<String>();
File actualInputFile = new File("C:/Desktop/example.java");
PrintWriter resultingSpreadsheet= new PrintWriter("C:/Desktop/SpreadsheetValues.txt", "UTF-8");
FileReader fr = new FileReader(actualInputFile);
BufferedReader br = new BufferedReader(fr);
String line=null;
while ((line = br.readLine()) != null) {
// code that makes ArrayList
}
for (int i = 0; i < exampleArrayList.size(); i++) {
resultingSpreadsheet.println(exampleArrayList.get(i));
}
resultingSpreadsheet.close();
The problem is that when i run this, nothing gets printed to the resultingSpreadsheet. It's completely empty.
BUT, this program works perfectly (meaning that it prints out everything correctly to the resultingSpreadsheet file) when I replace:
File actualInputFile = new File("C:/Desktop/example.java");
which is the file that I want as my input file, and which has a size of 481 KB,
with:
File smallerInputFile = new File("C:/Desktop/smallerExample.txt");
which is really just a smaller .txt example version of the .java source file, and it has a size of 1.08 KB.
I've tried a few things including flushing the PrintWriter, wrapping it around FileWriter, copy-pasting all the code from the .java file into a text file in case it was an extension problem, but these don't seem to work.
I'm starting to think it must be because of the size of the file that the PrintWriter makes, but it's very possible that that's not the problem. Perhaps I need to put everything in a stream (like it says here: http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html)? If so, how would I do that?
Why is reading the bigger actualInputFile and outputting its data correctly such a problem, when everything works fine for the smallerInputFile?
Can anyone help with this?
Check for exceptions while writing to the the excel sheet , because i really don't think its a problem of size. Below is the sample code that is executing successfully and the file size was approx 1 MB.
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("D:\\AdminController.java"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
This should go as a comment, but I do not have the rep. In the documentation it has both write methods and print methods. Have you tried using write() instead?
I doubt it's the size of the file, it may be between the two files you are testing one is .txt, and the other is .java
EDIT: Probably second suggestion of the two. First is just something I noticed with the docs.
The methods of PrintWriter do not throw Exception. Call the checkError() method which would flush the stream as well as return true if an error occurred. It is quite possible that an error occurred processing the larger file, an encoding error for instance.
Check your program. When the file is empty it means that your program doesn't close the PrintWriter before finishing the program.
For example you may have a return in a part of your program which cause that resultingSpreadsheet.close(); have not being run.
Here is a simple piece of code:
import java.io.*;
public class Read {
public static void main(String[] args) {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String x = null;
try{
x = f.readLine();
}
catch (IOException e) {e.printStackTrace();}
System.out.println(x);
}
}
}
I execute this as : java Read < input.txt
Once the input.txt is completely piped into the program, x keeps getting infinite nulls. Why is that so? Is there a way by which I can make the Standard In(Command Line) active after the file being fed into the code is done?
I've tried closing the stream and reopening, it doesn't work. Reset etc also.
By executing "java Read < input.txt" you've told the operating system that for this process, the piped file is standard in. You can't then switch back to the command line from inside the application.
If you want to do that, then pass input.txt as a file name parameter to the application, open/read/close the file yourself from inside the application, then read from standard input to get stuff from the command line.
Well, this is typical for reading in a BufferedReader. readLine() returns null when end of stream is hit. Perhaps your infinite loop is the problem ;-)
// try / catch ommitted
String x = null;
while( (x = f.readLine()) != null )
{
System.out.println(x);
}
You need to terminate your while loop when the line is null, like this:
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
catch (IOException e) {
logger.error("IOException reading System.in", e);
throw e;
}
finally {
if (in != null) {
in.close();
}
}
Is there a way by which I can make the Standard In(Command Line)
active after the file being fed into the code is done?
Sorry to bump an old question, but none of the answers so far points out that there is a (shell-only) way to pass back to console input after piping in a file.
If you run the command
{ cat input.txt & cat; } | java Read
then the text from input.txt will be passed to java Read and you will then be dropped back to console input.
Note that if you then press Ctrl+D, you will get the infinite loop of nulls, unless you modify your program to end the loop when it receives null.