Why it says the file is empty? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a method that writes integer array into a file.
When I read it with a method that brings those ints as array it's working.
But when I try to count how many ints it says it's empty.
The same code is written on other computer systems. and it's working for him, the SAME code!
I already put the "buffer" byte array into the read method. still not working
File file = new File("/home/arad/Desktop/intFile.bin");
int[] arr = {1,2,3,4,5,6};
//exampleWriteIntegerArray(arr, file);
reverseThisFile(file);
static void reverseThisFile(File file){
File newFile = new File("/home/arad/Desktop/newIntegerFile.bin");
InputStream inputStream = null;
OutputStream outputStream = null;
int counter = 0;
System.out.println(file.length());
try {
inputStream = new FileInputStream(file);
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[4];
int actuallyRead;
while((actuallyRead = inputStream.read()) != -1){
counter++;``
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(counter);
}

Is something wrong in lines (input and output files are same):
inputStream = new FileInputStream(file);
outputStream = new FileOutputStream(file); //comment this line
Name your variables better (outputFile, inputFile)... Also output stream outputStream is not closed... Try first just to print on console, ...

he uses Windows i use Ubuntu
I suspect this is the root of the difference, in conjunction with this code:
inputStream = new FileInputStream(file);
outputStream = new FileOutputStream(file);
In the first line, you're opening the existing file to read it. In the second line, you're creating a new, empty file. Should inputStream read from that empty file, or from the file that existed before you created the new one? I believe that the behaviour of Windows and Linux (and their file systems) may differ there.
I would strongly suggest that you don't do that.
Two alternative options:
Use two different files. Read from one, write to the other.
Do all the reading first, then do all the writing.
In both of these options, you never have an input and output stream to the same file at the same time... it's that part that's the recipe for problems.

Related

How to read zero-length file from /sys/fs/cgroup/ in Java? [duplicate]

This question already has answers here:
How do I read / convert an InputStream into a String in Java?
(62 answers)
Closed 4 years ago.
I'd like to read the content of the /sys/fs/cgroup/ files (eg. cpuacct.usage) from Java. I've already implemented the reading algorithm based on this answer.
The issue is that the cgroup files have 0 length by default. Each of the algorithms listed in the linked answer determines the size of the file before start to read from it, and because the file.length() returns 0, it will attempt to read 0 bytes from the file.
Here is the reading algorithm:
private String readFile(File file) {
DataInputStream stream = null;
String content = "";
try {
stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
final byte[] data = new byte[(int) file.length()]; // new byte[1024] throws exception
stream.readFully(data);
content = new String(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content;
}
The following approach (using Java NIO) works, even though the OS reports the file length as 0:
String file = "/sys/fs/cgroup/cpu,cpuacct/cpuacct.usage";
String content = new String(Files.readAllBytes(Paths.get(file)));
System.out.println(content); // 972897369764987
I recommend the IOUtils class in the Apache Commons IO library.
As the content of those files is text, you can use the IOUtils.toString method.
String content = IOUtils.toString(new FileInputStream(file), "UTF-8");

How do I read a text file using the read() method? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Suppose my text file name is "FileToUse". How do I read this file byte by byte using the read method from the FileInputStream class?
My end goal is to create a HashMap with the key as the letter (but the byte for the letter would be the key) and the value as the number of times the letter was in the text file. Any tips on how to do this would be appreciated.
Here is what you do:
First you create a file
Then, you link the file to the fileInputStream
If the file links then you assign the file contents one by one using the read() at the same time checking if it isn't the EOF. read() returns -1 for EOF
Then you process the contents into the map
File file = new File("FileToUse.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
int content;
while ((content = fis.read()) != -1) {
// process the content into the hashmap
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

What is the meaning of the compiler error "variable x may not have been initialized"

I'm trying to write a Java Android program that can read and write to a file. I'm having some issues though. When the line at the very end is run, Eclipse tells me that my totalString variable may not have been initialized. However, I assign it a value inside the try loop. When I remove that last line and run my program, my console displays "Read File Successfully", as well as "java.io.FileInputStream#d77ffd1". That's definitely not the value I wrote to the file. I don't know what I'm doing wrong here and I'm kind of losing my mind lmao. Additionally, if I try to put a line like
totalString = "A Test Value"
In the try block, I still get the same error. Any help would be greatly appreciated.
//lets try WRITING the file
Context context = getApplicationContext();
String filename = "balance";
String balanceString = "0.00";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(balanceString.getBytes());
outputStream.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Error in Writing File.");
}
//lets try READING the file
String totalString;
FileInputStream inputStream;
try {
inputStream = openFileInput(filename);
inputStream.read();
inputStream.close();
totalString = inputStream.toString();
System.out.println("Read File Successfully");
System.out.println(totalString);
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Error in Reading File.");
}
System.out.println(totalString);
inputStream.toString() returns a string representing the id of the InputStream object. Not the data inside the file.
If you want the data inside the File which you are reading from the InputStream, you need to use built-in methods to read the file. The easiest way to do so is to wrap the InputStream object inside a BufferedReader (or any other Reader object), then use the .readLine() (or equivalent) method to get the data.
For example:
String totalString;
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(openFileInput(filename)));
totalString = in.readLine();
in.close();
System.out.println("Read File Successfully");
System.out.println(totalString);
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Error in Reading File.");
}
Now for output:
You could use the exact same technique as before, only changing the objects to their 'Writer' equivalents. For example:
PrintWriter out;
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(penFileOutput(filename, Context.MODE_PRIVATE))));
out.println(balanceString);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Error in Writing File.");
}
The purpose of using the PrintWriter here in addition to the BufferedWriter is because it provides very easy to use methods (i.e. println()). Also, the 'flush()' method is used to make sure all the data in the stream gets written to the file, rather than 'getting stuck' in the buffer.
EDIT: Forgot to add a 'new' before the BufferedReader above. Fixed.
inputStream.read() MIGHT throw an Exception. In this case, the variable MIGHT not have be initialized. Just change the declaration to
String totalString = null;
Alternatively you can move the System.out.println to the end of the try-block, where, when reached because no Exception is thrown, the variable is initialized.
Also, read some tutorials about reading and writing files.
inputStream.read() will read a byte from the stream. But if you don't assign the return value of that function to a variable, it is discarded.
inputStream.toString() does what it says. It tries to describe the object, not the contents of the stream.
I would do it like that
FileOutputStream outputStream=new FileOutputStream(filename);
ObjectOutputStream stringSaver = new ObjectOutputStream(outputStream);
stringSaver.writeObject(balanceString);
stringSaver.close();
outputStream.close();
All this in a try catch for saving in a file the String then load it with
FileInputStream inputStream = new FileInputStream(filename);
ObjectInputStream objectStream = new ObjectInputStream(inputStream);
totalString = (String) objectStream.readObject();
objectStream.close();
inputStream.close();
this also in try catch...
It should work.
The problem solves that there was one variable may not have been initialized.
When you dont understand one part of the code be free to ask :D

JAVA What am I doing wrong, I want the line [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to make a change log and so I need a single line between some sentences.
All I have is this but it doesn't seem to work. Can anyone help me please?
#Test
public void addLine() {
File temp;
try {
temp = File.createTempFile("app.log", ".tmp", new File("."));
File appLog = new File("app.log");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
BufferedReader br = new BufferedReader(new FileReader(
appLog))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
if ("2 A".equals(line)) {
bw.write("New Line!");
bw.newLine();
}
}
appLog.delete();
temp.renameTo(appLog);
}
} catch (IOException e) {
e.printStackTrace();
}
}
The problem that you might be encountering might be because of the "line separator" used by the BufferedWriter (it gets set when you create said class). I think it would be best to use instead:
System.getProperty("line.separator");
This way you use the System's line separator rather than a hard coded one.
So that your code would look like this:
public void addLine() {
String lineseparator=System.getProperty("line.separator");
// I'd suggest putting this as a class variable, so that it only gets called once rather
// than
// everytime you call the addLine() method
try {
FileWriter stream = new FileWriter(this.log, true);
//If you don't add true as the second parameter, then your file gets rewritten
// instead of appended to
BufferedWriter out = new BufferedWriter(stream);
out.write(lineseparator); //This substitutes your out.newline(); call
out.close();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
##############################################################################.
I will try to be as brief and clear as possible.
I assume that you are opening a file that in my code I call "test.txt" and it's got about a paragraph or so. And that you want that outputted to another file, but with "empty lines" at some points.
Because File() is read line by line, it is much easier to open your main file read a line, and then write it to your log file, then analyse if an empty line is necessary and place it.
Let's see some code then.
// Assume you have a private class variable called
private String lineseparator=System.getProperty("line.separator");
// This method is in charge of calling the method that actually carries out the
// reading and writing. I separate them both because I find it is much cleaner
// to have the try{}catch{} blocks in different methods. Though sometimes for
// logging purposes this is not the best choice
public void addLines() {
try {
readAndWrite();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// This method is in charge of reading one file and output to another.
public void readAndWrite() throws IOException {
File test = new File("test.txt");
FileWriter writer = writer = new FileWriter(new File("log.txt"), true);
//This FileWriter is in charge of writing to your log file
String line;
boolean conditionToWriteNewLine=true;
//Obviously this needs to be changed to suit your situation
// I just added it for show
BufferedReader reader = new BufferedReader( new FileReader (test));
BufferedWriter out = new BufferedWriter(writer);
//It is in this while loop that you read a line
// Analyze whether it needs to have a new line or not
// and then write it out to log file
while( ( line = reader.readLine() ) != null ) {
out.write(line);
if(conditionToWriteNewLine){
out.write(this.lineseparator);
out.write(this.lineseparator);
//You need to write it twice for an EMPTY LINE
}
}
reader.close();
out.close();
}
One of the big differences from this code is that I only open the files once, while in your code you open the log file every time you want to add a new file. You should read the documentation, so you'll know that every time you open the file, your cursor is pointing to the first line, so anything you add will be added to first line.
I hope this helped you understand some more.
I'm not totally sure what you are asking for, but have you tried setting the "append" flag on true, so the FileWriter will not start a new file, but append content to it at the end? This is done by calling the FileWriter(File, boolean) constructor:
public void addLine() {
try {
FileWriter stream = new FileWriter(this.log, true); // Here!
BufferedWriter out = new BufferedWriter(stream);
out.write("New Extra Line Here");
out.newLine();
out.close();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I need a single line between some sentences
I guess you mean a new line between other lines of the same file.
To do so you have to read the whole file, locate the place where you want to insert a line, insert the line then write the new content to the file.
This should work fine for small files but if you have large files you might get in trouble.
So you need a more scaleable way of doing it: Read line by line, and write write to a temp file. if you indentify the location where a new line should be inserted, write that line. Continue with the rest of the file. After you are done delete the original file and rename the temp file with the original name.
Pseudocode:
Open actual file
Open temp file
while not end of actual file
Read one line from actual file
Check if new line has to inserted now
Yes: write new line to temp
write line from actual to temp
Close actual file
Close temp file
Delete actual
Rename temp to actual
Code example: (unlike the pseudo code, the new line is inserted after)
Here the line "New Line!" is inserted after each line which is equal to "2 A".
#Test
public void insertNewLineIntoFile() throws IOException {
File temp = File.createTempFile("app.log", ".tmp", new File("."));
File appLog = new File("app.log");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
BufferedReader br = new BufferedReader(new FileReader(appLog))) {
String line;
while((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
if("2 A".equals(line)) {
bw.write("New Line!");
bw.newLine();
}
}
appLog.delete();
temp.renameTo(appLog);
}
}
Note that File#delete() and File#renameTo both return a boolean value that is true onyl if the operation was successfull. You absolutely need to check those retuned values and handle accordingly.
out.println("\n");
(instead of out.newLine();)
\n in java declares a new line. If you dont add any text before it then it should just print a blank line like you want.
This will work Correctly.
Suggestion:
out.close(); and stream.close(); should write inside finally block ie they should close even if some exceptions occured.

java.io.File getting extra char while writing into file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
Why I am getting extra char while writing into file for the following code? If I am using writeBytes(String) than the below code is working file. Then what is the problem with dos.writeChars() method?
File fileObj = new File("student.txt");
try {
// writing into file
FileOutputStream fos = new FileOutputStream(fileObj);
String msg = "This is student file";
DataOutputStream dos = new DataOutputStream(fos);
dos.writeChars(msg);
//reading from file
FileInputStream fis = new FileInputStream(fileObj);
DataInputStream dis = new DataInputStream(fis);
System.out.println(dis.readLine());
for (int i = 0; ((i = dis.read()) != -1); i++) {
System.out.println(i);
}
fos.close();
dos.close();
} catch (FileNotFoundException e) {
System.err.println("File not found!");
} catch (IOException e) {
e.printStackTrace();
}
writeChars() uses 2-byte chars (UTF-16). So each char you write will result in two bytes written.
If you want another encoding use getBytes() on the String and write it as bytes.

Categories