I have run into a situation when writing code in Java. The error mentions that in my code newLine() has private access in PrintWriter I have never gotten this error and it worries me as I cannot understand why newLine would be private to my variable PrintWriter
Below will be my error messages and part of my code where this issue comes from.
Errors:
:75: error: newLine() has private access in PrintWriter
savingsFile.newLine();
^
:77: error: newLine() has private access in PrintWriter
savingsFile.newLine();
^
:96: error: cannot find symbol
while((str1=savingsFile.readLine())!=null){
^
symbol: method readLine()
location: variable savingsFile of type Scanner
3 errors
Code:
public static void writeToFile(String[] months, double[] savings) throws IOException{
PrintWriter savingsFile = null;
try {
savingsFile = new PrintWriter(new FileWriter("E:/savings.txt", true));
} catch (IOException e) {
e.printStackTrace();
}
//code to write to the file and close it
int ctr = 0;
while(ctr<6){
savingsFile.write(months[ctr]);
savingsFile.newLine();
savingsFile.write(savings[ctr]+"");
savingsFile.newLine();
ctr = ctr + 1;;
}
savingsFile.close();
}
public static void readFromFile(String[] months, double[] savings) throws IOException{
String str1, str2;
Scanner savingsFile = null;
try {
savingsFile = new Scanner(new File("E:/savings.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//code to read the file, load data in the array and close file
str1 = savingsFile.nextLine();
System.out.println(str1);
int ctr = 0;
while((str1=savingsFile.readLine())!=null){
System.out.println(str1);
}
savingsFile.close();
}
PrintWriter does not have a public newLine() method (see the Javadoc). Just write a newline character "\n" to make a new line, or call println() with no arguments.
Scanner does not have a readLine() method. You probably meant nextLine()
It seems like newLine() is a private method in PrintWriter what means that you can't invoke it externally from some other class that instantied PrintWriter as object.
Related
im writing a program that subs out any spaces with hypens. The program compiles but it inserts a hyphen at the beginning of the program instead of every instance of a space the source code is as follows:
package Exercises;
import java.io.*;
import java.util.Scanner;
public class filehyphen {
public static void main(String[] args)
throws IOException{
DataOutputStream wr;
DataInputStream re;
Scanner type = new Scanner(System.in);
FileOutputStream text;
FileInputStream open;
String OgTxt;
try {
wr = new DataOutputStream(new FileOutputStream("random.txt"));
System.out.println(" Type whatever youd like");
OgTxt = type.nextLine();
wr.writeUTF(OgTxt);
System.out.println(" heres what you typed : " + OgTxt);
wr.close();
type.close();
}
catch(IOException exc) {
System.out.println("cannot write to this file");
}
System.out.println("heres what the text would be with spaces as hyphens");
try {
re = new DataInputStream(new FileInputStream("random.txt"));
OgTxt = re.readUTF();
if(OgTxt.contains(" ")) {
System.out.print("'");
System.out.println(OgTxt);
re.close();
}
}
catch(IOException exc) {
System.out.println("Read error");
}
I think it has something to with the contains method but im not sure. Answers appreciated. Thanks you!!
I have provided the Main method below for your solution.
public static void main(String[] args) throws IOException{
DataOutputStream wr;
DataInputStream re;
Scanner type = new Scanner(System.in);
FileOutputStream text;
FileInputStream open;
String OgTxt;
try {
wr = new DataOutputStream(new FileOutputStream("random.txt"));
System.out.println("Type whatever youd like");
OgTxt = type.nextLine();
wr.writeUTF(OgTxt);
System.out.println("heres what you typed : " + OgTxt);
wr.close();
type.close();
}
catch(IOException exc) {
System.out.println("cannot write to this file");
}
System.out.println("heres what the text would be with spaces as hyphens");
try {
re = new DataInputStream(new FileInputStream("random.txt"));
OgTxt = re.readUTF();
String replacedString = OgTxt.replace(" ", "-");
System.out.println(replacedString);
re.close();
}
catch(IOException exc) {
System.out.println("Read error");
}
}
I removed the if statement in your second try...catch block and made use of the replace method provided natively by the String class.
In your post you say that spaces should be replaced by hyphens, however you are trying to replace spaces with single quotation marks. Assuming you meant hyphens I corrected that.
When I try to run this code through eclipse, it works fine, but when I try to run it through CMD using "java MainClass >result.txt" I get a FileNotFoundException.
This is the code in question:
import java.io.;
import java.util.;
public class MainClass
{
static int cellNumber;
static int freeSpace;
static int randomResult;
static int chosen;
static int choiceSize;
public static void main(String[] args)
{
Scanner in = null;
try
{
in = new Scanner(new FileReader("C:\\users\\Alon\\workspace\\ex2temp\\bin\\input.txt"));
FileWriter fw = new FileWriter("C:\\users\\Alon\\workspace\\ex2temp\\bin\\result.txt");
PrintWriter pw = new PrintWriter(fw);
chosen = getRandomInt();
pw.printf("Choice=%d", chosen);
pw.println();
while (in.hasNext())
{
cellNumber = in.nextInt();
freeSpace = in.nextInt();
if (sizeOfChosen(chosen) <= freeSpace)
{
pw.printf("%d", cellNumber);
pw.println();
break;
}
}
if (!in.hasNext())
{
pw.println("Cannot allocate memory");
pw.println();
}
pw.close();
fw.close();
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Can anyone help please? Thanks :)
You're using the files from the ".../ext2temp/bin/.." which I assume it's Eclipse's output folder. Use the path where you have the original files.
In order to create a continuous writing on the same file, I had to append text into the existing file. I have added ", true" when creating the FileWriter. Then, I created a new BufferedWriter which received the FileWriter object, and finally, changed the PrintWriter receiving object to the bufferredWriter. This way, every time I run the program, 2 new lines of data are formed below the old ones and I get a "log file".
I'm trying to implement a method to write an array of Song() objects to a file for an assignment. I've become fairly lost on how to achieve this. I want to be able to call the function in the main method but it doesn't appear to do anything. At this stage it is a test where I want it to print on the command line upon running main().
Here's my code:
public static void main (String[] args)
{ //run the main program.
Interface songUI = new Interface();
songUI.run();
try{
PrintWriter outputTest = null;
outputTest = write("testfile");
read();
}
catch(IOException e){
System.out.println("Caught!");
}
}
public static PrintWriter write (String fileName) throws IOException{
Scanner console = new Scanner(System.in);
PrintWriter outFile = new PrintWriter(fileName);
outFile.println ("Random numbers");
for(int i=0; i<10; i++)
{
outFile.println ((int)( 1 + Math.random()*10) + " ");
}
outFile.close();
return outFile;
}
I also have a method for reading from the file i'm trying to get working here:
public static void read() throws IOException{
String fileName = "test1";
System.out.println ("The file " + fileName + "\ncontains the following lines:\n");
Scanner inputStream = new Scanner (new File (fileName));
while (inputStream.hasNextLine ())
{
String line = inputStream.nextLine ();
System.out.println (line);
}
inputStream.close ();
}
As you can tell i'm confused, and any help would be amazing. Thank you.
You are writing to testfile but trying to read from test1.
The code is poorly organized.
a method called write() shouldn't do anything else, and it should certainly not do input
returning a closed PrintWriter is completely pointless.
the write() method catches IOException internally, which makes it impossible for the caller to know about failure. Have it throw IOException instead, like the read() method does, and let the caller deal with it.
Main:
package main;
import racreader.RAFReader;
public class RandomAccessFile {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Wrong arguments length");
System.exit(1);
}
try {
RAFReader reader = new RAFReader (args[0]);
try {
String output = reader.readUTF(Integer.parseInt(args[1]));
System.out.print(output);
} catch (Exception e) {
System.err.println(e.toString());
} finally {
reader.close();
}
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
RAFReader:
package racreader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RAFReader {
private final String fileName;
private final RandomAccessFile reader;
public RAFReader(String fileName) throws FileNotFoundException {
this.fileName = fileName;
this.reader = openFile();
}
private RandomAccessFile openFile() throws FileNotFoundException {
RandomAccessFile reader = new RandomAccessFile(fileName, "r");
return reader;
}
public String readUTF(int offset) throws IOException {
reader.seek(offset);
String output = reader.readUTF();
return output;
}
public void close() throws IOException {
reader.close();
}
}
The problem is in EOFException in every file (even encoded in UTF8) and every offset. Why?
UPD: I try to get my program working with file with this content:
Это тест UTF-8 чтения
It works fine only if offset = 0. Any other offset throws EOFException.
The readUTF()/writeUTF() methods from RandomAccesFile use conventions for writing Java String objects, which are not necessarily honored by UTF encoded text files. readUTF() was not meant to be used for reading arbitrary text file, which was not originally written by using RandomAccesFile.writeUTF().
As method Javadocs specify, readUTF() assumes that the first two bytes it reads contain the number of bytes in the following string. This is the case if the string was written to file by the pairing writeUTF() method, but in case of the text file this will throw intermittent EOFException, since the first two bytes will contain actual characters from the string.
In your case, a different set of classes can solve the problem. Consider rewriting RAFReader class using InputStreamReader:
public String readUTF(int offset) throws IOException {
FileInputStream is = new FileInputStream(fileName);
Reader fileReader = new InputStreamReader(is, "UTF-8");
StringBuilder stringBuilder = new StringBuilder();
fileReader.skip(offset);
int charsRead;
char buf[] = new char[256];
//Read until there is no more characters to read.
while ((charsRead = fileReader.read(buf)) > 0) {
stringBuilder.append(buf, 0, charsRead);
}
fileReader.close();
return stringBuilder.toString();
}
If using RandomAccesFile is a must, you can use input stream which wraps the RandomAccesFile. The simplest way to do it is through FileChannel, encapsulated by RandomAccesFile:
InputStream is = Channels.newInputStream(reader.getChannel());
EOFException - if this file reaches the end before reading all the
bytes.
One possible way in which you got EOFException is at line
reader.seek(offset);
String output = reader.readUTF();
Maybe the offset value is high for file length. Try with offset = 0 and check if you get EOF or not.
I'm new to Java and am trying to write a program that has one argument, the path of a text file. The program will locate the text file and print it out to the screen. Eventually I'm going to build this to format the given text file and then print it out to an outfile, but I'll get there later.
Anyways my program is always throwing and IOException and I'm not sure why. Given the argument C:\JavaUtility\input.txt , I receieve "Error, could not read file" during runtime. My code is located below.
import java.io.*;
public class utility {
public static void main(String[] path){
try{
FileReader fr = new FileReader(path[0]);
BufferedReader textReader = new BufferedReader(fr);
String aLine;
int numberOfLines = 0;
while ((aLine = textReader.readLine()) != null) {
numberOfLines++;
}
String[] textData = new String[numberOfLines];
for (int i=0;i < numberOfLines; i++){
textData[i] = textReader.readLine();
}
System.out.println(textData);
return;
}
catch(IOException e){
System.out.println("Error, could not read file");
}
}
}
[EDIT] Thanks for all the help everyone! So given my end goal, I thought it would still be useful to find the number of lines and store in a finite array. So I ended up writing two classes. The first, ReadFile.java found the data I wanted and handles most of the reading. The second FileData.java invokes the methods in ReadFile and prints out. I've posted them below incase someone later finds them useful.
package textfiles;
import java.io.*;
public class ReadFile {
private String path;
public ReadFile(String file_path){
path = file_path;
}
int readLines() throws IOException{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while ((aLine = bf.readLine()) != null){
numberOfLines++;
}
bf.close();
return numberOfLines;
}
public String[] OpenFile() throws IOException{
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
for(int i=0; i < numberOfLines; i++){
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
}
package textfiles;
import java.io.IOException;
public class FileData {
public static void main(String[] args)throws IOException{
String file_name = args[0];
try{
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
for(int i=0; i < aryLines.length; i++){
System.out.println(aryLines[i]);
}
}
catch (IOException e){
System.out.println(e.getMessage());
}
}
}
You're at the end of the file. When you determine the number of lines in the file, you've read until the end of the file,and the EOF Flag is set. [Edit: As #EJP notes below, BufferedReader returns null reading past the end of a file. The fact your reader isn't where you want it, however, remains true.] In the past, I've hacked around this simply by closing and re-opening the file. Alternatively, look into Array Lists or simple Lists. They're dynamically re-sizing, so you don't need to know the number of lines in the file ahead of time.
As mentioned by #mikeTheLiar you are at End Of File. BufferedReader reference is File Handler with an internal cursor pointing to current position in file. As you fire readLine() method, the pointer reads characters till it reaches new line character, returning the string. The pointer is set to new position. Once you read all the lines then readLine() returns null. After that if you call readLine() it will throw IOException. As noted by #EJP
One of the best coding rules while using IO API is to always check for EOF condition - the way you have in first loop. Once you reach EOF after that you should not call read method on the same reference without resetting the cursor - this can be done by calling reset() method.
IMHO, in your case there is no need for second loop. You can achieve the functionalty using one loop only.
import java.io.*;
import java.util.ArrayList;
public class utility {
public static void main(String[] path){
try{
FileReader fr = new FileReader(path[0]);
BufferedReader textReader = new BufferedReader(fr);
String aLine;
int numberOfLines = 0;
ArrayList readLines = new ArrayList();
while ((aLine = textReader.readLine()) != null) {
numberOfLines++;
readLines.add(aLine);
}
//Assuming you need array of lines, if not then you can print the lines directly in above loop
String[] textData = readLines.toArray();
System.out.println(textData);
return;
}
catch(IOException e){
System.out.println("Error, could not read file");
}
}
}
EDIT
I tried your code - it is working fine and printing the array reference. As suggested in comments the problem is with source (file might not be readable due to security or any other reason) - if you can print the exception message and get the exact line number where exception is thrown it would be helpful.
Couple of observations apart from the IO exception:
You are trying to open the file twice. readLines() method is called from within OpenFile(). Following the sequence of code file is first opened in OpenFile() when you create textReader. After that you are calling readLines() which is again trying to open the file when you create file_to_read.
You should try to avoid that and in your flow you should call int numberOfLines = readLines(); before FileReader fr = new FileReader(path);
Again IMHO there should be only one method and you should iterate over the file only once - both from efficience/performance and code maintainability perspective. You can change your ReadFile class as follows:
package textfiles;
import java.io.*;
import java.util.ArrayList;
public class ReadFile {
private String path;
public ReadFile(String file_path){
path = file_path;
}
//You need not have separate file for counting lines in file
//Java provides dynamic sized arrays using ArrayList
//There is no need to count lines
public String[] OpenFile() throws IOException{
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
ArrayList fileLines = new ArrayList();
String readLine = textReader.readLine();
while(readLine != null){
fileLines.add(readLine);
readLine = textReader.readLine();
}
textReader.close();
return fileLines.toArray();
}
}
Another small observation: in some places the java variable naming conventions are not followed. OpenFile() method should be openFile() and file_to_read should be fileToRead
Contrary to several answers here, readLine() does not throw an exception at end of file, it just keeps returning null. Your problem is being masked by another one. Never just make up your own error messages. Always print the one that comes with the exception. If you had done that you would probably have found the problem immediately. Almost certainly you weren't able to open the file at all, either because it wasn't there or you didn't have read access. The exception will tell you.