Content can not be resolved - java

While building package in eclipse:
public static String getContents(File aFile)
{
contents = new StringBuffer();
BufferedReader input = null;
try
{
input = new BufferedReader(new FileReader(aFile));
String line = null;
while ((line = input.readLine()) != null) {
contents.append(line);
}
return contents.toString();
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
try
{
if (input != null) {
input.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
we are getting following three errors:
contents can not be resolved (On line number 10)
contents can not be resolved (On line number 12)
contents can not be resolved to a variable (On line number 3)
We are using Eclipse Neon (4.6.0) and java jdk1.8.0_102
Already tried clean and refresh in Eclipse

You define contents variable wrong. To define variable in Java you need to start with a type, then variable name and initializing expression (which is optional by the way).
So contents must be defined as follows:
StringBuffer contents = new StringBuffer();
Edit
If you don't need synchronization support you should use StringBuilder class instead of StringBuffer

Related

Why i got a null message when retrieveng an string line from a file in java

I tried to retrieve a single line of text from a text file in java, and indeed i got what i expect but at the end it adds a null reference, but i don't know why. here my code:
public class EncryptDecryptFile {
public void writeDecryptionFile(String message) {
File f;
FileWriter writeArchive;
try {
f = new File("C:\\Users\\Dell\\Training\\DecryptionFile.txt");
writeArchive = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(writeArchive);
PrintWriter text = new PrintWriter(bw);
text.write(message+"\n");
text.close();
bw.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
public String readEncryptionFile() {
File file = new File("C:\\Test\\EncryptionFile.txt");
String line = "";
try (
BufferedReader br = new BufferedReader(new FileReader(file))) {
while (true) {
line = br.readLine();
if (line != null) {
System.out.print(line);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
public static void main(String[] args) {
EncryptDecryptFile file = new EncryptDecryptFile();
file.writeDecryptionFile("Hello World!!!");
System.out.println(file.readEncryptionFile());
}
}
The result is as follows
Hello World!!!
null
Where is that null coming from ?
I appreciate any help :(
You are returning line and printing it at the end of System.out.println(file.readEncryptionFile()); at that time it must be null (or the loop would not end). Solution, don't print it. Just do
file.readEncryptionFile();
Note: You also print with-in readEncryptionFile()
Do not do
System.out.println(file.readEncryptionFile());
You are already printing it out in this method, so just calling
file.readEncryptionFile();
should suffice.
Of course you do not need to return a String from this method.
Alternative in the readEncryptionFile, create a StringBuilder Object and append to that if the line is not null, then return the String of the StringBuilder Object.

formatting while writing a document

I am reading a txt file into a String buffer and writing the content into a word document using OutputStreamWriter.
The problem is that the formatting is not retained in the document. The spaces and the line breaks are not retained as in the text file. The txt file is formatted properly with spaces, page breaks, and tabs. I want to replicate the txt in word document. Please suggest how can the same formatting be retained. The link to the file is: http://s000.tinyupload.com/index.php?file_id=09876662859146558533.
This is the sample code:
private static String readTextFile() {
BufferedReader br = null;
String content = null;
try {
br = new BufferedReader(new FileReader("ORDER_INVOICE.TXT"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
sb.append(System.lineSeparator());
}
content = sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}
private static void createDocument(String docName, String content) {
FileOutputStream fout = null;
try {
fout = new FileOutputStream(docName);
OutputStreamWriter out = new OutputStreamWriter(fout);
out.write(content);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Try to change your readTextFile() like this and try.
BufferedReader br = null;
String content = null;
try {
br = new BufferedReader(new FileReader("ORDER_INVOICE.TXT"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while(line != null) {
content += line + "\n";
line = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
Actually if your using java 7, you can use try-with-resources in order to decrease the number of lines in your code.
Try to avoid printing \n chars. Use \r\n for Windows - remember that line separators differ across platforms.
A more reliable way is to use PrintWriter, see
How to write new line in Java FileOutputStream
After the discussion in comments:
the source file has unix line breaks
the output file is expected to have Windows line breaks
we shall strip the 0x0c (form feed - i.e. move to next page on the printer) from the source file, as it is non-printable.
public static void main(String[] args) throws IOException {
String content = new String(Files.readAllBytes(Paths.get("f:\\order_invoice.txt")))
.replace("\u000c","");
PrintWriter printWriter=new PrintWriter(new FileWriter("f:\\new_order_invoice.txt"));
for (String line:content.split("\\n")) {
printWriter.println(line);
}
printWriter.close();
}
So:
read the file as it is into a String
get rid of the form feed (0x0c, unicode u000c)
split the string at unix line breaks \n
write it out line by line using PrintWriter which uses the platform default line ending, i.e. windows cr-lf.
Remember that you can actually do this in one line, using a regexp to replace unix line endings to windows line endings in the string representing the whole file, and use Files.write to write out the whole file in one line. However this presented solution is probably a bit better as it always uses platform native line separators.

Reading from a text file with spaces and then putting into arrayList

I have spent the last week trying to figure out how to make this stupid code work. I have managed to get everything to work except for reading from my text file. It can read an individual integer on a line, but when given a line with multiple integers separated by spaces, it freaks out. Now I've gone and tried to fix it and the code won't even compile anymore. Only one line is causing problems.
I'm not good at coding, so I don't know where to begin. Yes, I've looked this up online. Yes, I've checked the forums. Yes, I have tried multiple different methods to make this work....
How do I fix this?? :(
ArrayList<Integer> list = new ArrayList<Integer>();
// the above line is in a different method in the same class, but it's relevant here
File file = new File("C:\\Users\\Jocelynn\\Desktop\\input.txt");
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null)
{
// I want the following line to read "218 150 500 330", and to store each individual integer into the list. I don't know why it won't work :(
list.add(Integer.parseInt(src.next().trim()));
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
//print out the list
System.out.println(list);
Thank you for the help! I'm sure that I'm just missing something really simple...
You can use a Scanner(String) like
while ((text = reader.readLine()) != null) {
Scanner scanner = new Scanner(text);
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
}
Of course, your entire method could be simplified by using a try-with-resources Statement and the diamond operator and just Scanner(File) like
public static void main(String[] args) {
File file = new File("C:\\Users\\Jocelynn\\Desktop\\input.txt");
List<Integer> list = new ArrayList<>();
try (Scanner scanner = new Scanner(file);) {
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
} catch (Exception e) {
e.printStackTrace();
}
// print out the list
System.out.println(list);
}
Do this inside the while loop
String[] individualArray = text.split(" ");//note space
for(String individual:individualArray){
yourList.add(individual);//You need to parse it to integer here as you have already done
}
In the above code, individualArray will contain each individual integers that are separated by space. And inside the for loop each string needs to be parsed to integer and then added to your list
try this :
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
File file = new File("C:\\Users\\Jocelynn\\Desktop\\input.txt");
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null)
{
// you need only this for loop in you code.
for (String value : text.split(" ")) { // get list of integer
if(!value.equals("")) // ignore space
list.add(Integer.parseInt(value)); // add to list
}
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
try
{
reader.close();
} catch (IOException e)
{
e.printStackTrace();
}
// print out the list
System.out.println(list);
}

Initialization in while block?

Isn't there a cleaner way of doing the following (eliminating the need for initializing line prior to the while block)? It just seems unnecessary to intialize a variable prior to its usage instead of doing something like while ((String line = br.readLine) != null) {}. If not, why not?
BufferedReader reader = null;
try
{
File file = new File("sample-file.dat");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
No, you cannot avoid initializing the variable. However, you can use Try-With-Resources to make it a lot cleaner.
try (BufferedReader reader = new BufferedReader(new FileReader("sample-file.dat"))) {
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
Just adding this for completions sake, if anyone is using Java 8, you have access to the Stream API. Using this you can just simply do the following:
BufferedReader reader = new BufferedReader(...);
reader.lines().forEach(System.out::println);
And if you're wondering, the code under the hood that produces this does check for null lines.
No you can't declare (and use) a variable in the while loop expression evaluation step. But, you can eliminate the finally block by using a try-with-resources
try (
File file = new File("sample-file.dat");
BufferedReader reader = new BufferedReader(new FileReader(file));
) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
No, you can't declare a variable inside the condition definition except in a for loop. Can't really say why - perhaps because the condition is not supposed to be somewhere you initialize things, whereas a for initialization step is.
But anyway, especially in cases where the loop conditions are complicated, some coders prefer to use
while (true) {
String line = reader.readLine();
if ( line == null )
break;
System.out.println(line);
}
But it's really a matter of style.

Reading from a text file in java is returning some garbage value

I'm performing certain commands through command prompt and storing the values in a text file.
wmic logicaldisk where drivetype=3 get deviceid > drive.txt
Now I want to read the string stored in the text file from my java file. When I try to do this:
try {
File file = new File("drive.txt");
FileReader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader);
int i=0;
while ((string[i] = in.readLine()) != null) {
System.out.println(string[i]);
++i;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
I get the output as follows:
ÿþD[]E[]V[]I[]C[]E[]
how to avoid this?
while ((string[i] = in.readLine()) != null) {
System.out.println(string[2]);
}
over there you are missing the i++;
However I would advise you to use this structure: Use a ArrayList instead of an array, since this allows you to have a self-resizing structure, also instead in the while use the method ready(); from the BufferedRead in order to check the end from the document, at the end the for it's just to display the elements in String ArrayList.
ArrayList<String> string = new ArrayList<String>();
try {
File file = new File("drive.txt");
BufferedReader entrada;
entrada = new BufferedReader(new FileReader(file));
entrada.readLine();
while (entrada.ready()) {
string.add(entrada.readLine());
}
entrada.close();
} catch (IOException e) {
e.printStackTrace();
}
for (String elements : string) {
System.out.println(elements);
}
Why do you need a string array here? The size of the array may be wrong? Simply use a string instead of array. I tried this and works fine for me:
try {
String string;
File file = new File("drive.txt");
FileReader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader);
int i = 0;
while ((string = in.readLine()) != null) {
System.out.println(string);
++i;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
If you are using eclipse IDE, change the encoding type. Go to Edit->Set Encoding-> Others->UTF-8.

Categories