FileInputStream returns null - java

I have two methods, both using FileInputStream Objects.
The First one returns expected value. This method works fine.
But the Second method returns nothing. The value passed to the second method is not null.
I need to get the hexadecimal format of the files passed to methods.
Why is it so? Kindly Explain.
Here is my code
public String binaryFile1(File file1){
try{
stringBuilder1=new StringBuilder();
is1=new FileInputStream(file1);
while(b!=-1){
counter++;
b=is1.read();
String s = Integer.toHexString(b).toUpperCase();
if (s.length() == 1) {
stringBuilder1.append('0');
}
if(counter%5==0){
stringBuilder1.append(s).append("\n");
counter=0;
}else
stringBuilder1.append(s).append(' ');
}
is1.close();
}catch(Exception e){
e.printStackTrace();
}
return stringBuilder1.toString();
}
public String binaryFile2(File file2){
try{
stringBuilder2=new StringBuilder();
is2=new FileInputStream(file2);
while(b!=-1){
counter++;
b=is2.read(); //Here b does not get any content assigned.
String s = Integer.toHexString(b).toUpperCase();
if (s.length() == 1) {
stringBuilder2.append('0');
}
if(counter%5==0){
stringBuilder2.append(s).append("\n");
counter=0;
}else
stringBuilder2.append(s).append(' ');
}
is2.close();
}catch(Exception e){
e.printStackTrace();
}
return stringBuilder2.toString(); //Here stringBuilder2 is null
}

Since b is shared and you don't reset it after binaryFile1 it's still -1 at the start of binaryFile2. I suggest you use,
int b;
while ((b = is2.read()) != -1) {
// ...
}
Edit
It is important to close your resources when you're done. I also suggest you try and limit variable scope as much as possible. Using try-with-resources you could write binaryFile2 like
public String binaryFile2(File file) {
StringBuilder sb = new StringBuilder();
int counter = 0;
try (InputStream is = new FileInputStream(file)) {
int b;
while ((b = is.read()) != -1) {
counter++;
String s = Integer.toHexString(b).toUpperCase();
if (s.length() == 1) {
sb.append('0');
}
sb.append(s);
if (counter % 5 == 0) {
sb.append(System.lineSeparator());
counter = 0;
} else {
sb.append(' ');
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}

Related

BufferedReader causing Java GUI to hang

I am currently working on an add-on to a rhythm game called osu! using Java. There are multiple windows involved, but after the actionPerformed event listener is invoked for one of them, it creates another window that creates an object the constructor of which calls two methods that each use a BufferedReader. However, once I click the button for the actionPerformed, the program hangs and freezes until it is terminated from task manager. Here is the actionPerformed code for the GUI window:
private void btnCreateActionPerformed(ActionEvent evt) throws IOException {
String text = textBeats.getText();
if (text == null) {
JOptionPane.showMessageDialog(contentPane, "Please enter a positive number.");
}
boolean isNumber = true;
for (char c : text.toCharArray()) {
if (!Character.isDigit(c)) {
isNumber = false;
} else if (c == '-') {
isNumber = false;
}
}
if (isNumber) {
double beats = Double.parseDouble(text);
WindowCode window = new WindowCode(drawArea, file, beats);
window.setVisible(true);
this.dispose();
} else {
JOptionPane.showMessageDialog(contentPane, "Please enter a positive number.");
}
}
And here are the two methods called when creating WindowCode:
public double[] getLastTimingPoint() {
String line;
String timings[] = new String[8];
double pointElements[] = new double[8];
boolean isTiming = false;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(osuFile), "UTF-8"))){
while ((line = reader.readLine()) != null) {
if (line.contains("[TimingPoints]")) {
isTiming = true;
} else if (line.contains("[Colours]") || line.contains("[HitObjects]")) {
isTiming = false;
}
if (isTiming) {
if (!line.contains("[TimingPoints]") && !line.contains("[Colours]") && !line.contains("[HitObjects]") && line.length() > 0) {
timings = line.split(",");
}
}
}
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < timings.length; i++) {
pointElements[i] = Double.parseDouble(timings[i]);
}
System.out.println("1");
return pointElements;
}
public double[] getLastInheritedPoint() {
String line;
String timings[] = new String[8];
double pointElements[] = new double[8];
boolean isTiming = false;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(osuFile), "UTF-8"))) {
while ((line = reader.readLine()) != null) {
if (line.contains("[TimingPoints]")) {
isTiming = true;
}
while (isTiming) {
if (!line.contains("[TimingPoints]") && !line.contains("[Colours]") && !line.contains("-")) {
timings = line.split(",");
}
}
}
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < timings.length; i++) {
pointElements[i] = Double.parseDouble(timings[i]);
}
System.out.println("2");
return pointElements;
}
I have tried to print out checkpoint numbers and it only prints "1" to the console, leading me to believe that it is the second method that is causing this. My question is if the BufferedReader affects the EDT somehow and if it does, how I should get around it.
On the second method you have this inner loop:
while (isTiming) {
if (!line.contains("[TimingPoints]") && !line.contains("[Colours]") && !line.contains("-")) {
timings = line.split(",");
}
}
If the file being read contains this string "[TimingPoints]" then variable isTiming will be set to true, and no one else resets it back to false, being trapped into an infinite loop.
You should revise that loop logic.

reading a file in java and controlling an array list

I know my code is not optimal and there is certainly a better way to write what I am trying to do than how I have it written.
I am trying to setup a reader so that it inserts information into an array list. Right now my problem is that I cannot find out how to add an object to an array list only once. The last object of the file is filling the empty spaces of the arrayList.
public void readCharacterFile() {
String fileName = "C:/Users/brenton.reittinger/Desktop/characters.txt";
String line = null;
String fileContent = "";
try {
FileReader in = new FileReader(fileName);
BufferedReader bufferReader = new BufferedReader(in);
while((line = bufferReader.readLine()) != null) {
fileContent = fileContent + line;
}
bufferReader.close();
} catch(Exception e){
e.printStackTrace();
}
Character character = new Character();
Attributes attribute = new Attributes();
character.setAttribute(attribute);
String[] file = fileContent.split(":");
int count = 0;
for (String fileSection : file) {
if (fileSection.length() > 0) {
if(count == 5) {
character.getAttribute().setLevel(Integer.parseInt(fileSection));
count++;
}
if(count == 4) {
character.getAttribute().setExperience(Integer.parseInt(fileSection));
count++;
}
if(count == 3) {
character.getAttribute().setHealth(Integer.parseInt(fileSection));
count++;
}
if(count == 2) {
character.getAttribute().setAttack(Integer.parseInt(fileSection));
count++;
}
if(count == 1) {
character.setRace(fileSection);
count++;
}
if(count == 0) {
character.setName(fileSection);
count++;
}
}
}
user.addCharacterToList(character);
}
Why not using a java Set instead? Sets guarantee that each object instance can only occur once.

BufferedReader.readLine() pauses my application?

I am using this code:
while (true) {
sendData("hi");
System.out.println("Data sent!");
BufferedReader inFromServer;
try {
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e1) {
inFromServer = null;
e1.printStackTrace();
}
System.out.println("Recieved!"); //I see this de-bug message.
try {
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence); //I do NOT see this de-bug message!
} catch (IOException e) {
e.printStackTrace();
}
}
It successfully sends data to a server - And the server successfully sends data back:
public void run () {
//handle the session using the socket (example)
try {
sendData("Hi");
System.out.println("Data sent!"); //I see this de-bug message.
} catch (Exception e) {
e.printStackTrace();
}
}
However for some reason, the application seems to pause at the inFromServer.readLine() method. I see the "Recieved!" de-bug message, but not the "FROM SERVER" de-bug message.
There are no errors at all. It just seems to hang there.
Why is it hanging, and how can I fix that?
Well this simply means that inFromServer does not receive any line.
Make sure you really send a line,
Reads a line of text. A line is considered to be terminated by any one
of a line feed ('\n'), a carriage return ('\r'), or a carriage return
followed immediately by a linefeed.
Have a look at the readLine method :
String readLine(boolean ignoreLF) throws IOException {
StringBuffer s = null;
int startChar;
synchronized (lock) {
ensureOpen();
boolean omitLF = ignoreLF || skipLF;
bufferLoop:
for (;;) {
if (nextChar >= nChars)
fill();
if (nextChar >= nChars) { /* EOF */
if (s != null && s.length() > 0)
return s.toString();
else
return null;
}
boolean eol = false;
char c = 0;
int i;
/* Skip a leftover '\n', if necessary */
if (omitLF && (cb[nextChar] == '\n'))
nextChar++;
skipLF = false;
omitLF = false;
charLoop:
for (i = nextChar; i < nChars; i++) {
c = cb[i];
if ((c == '\n') || (c == '\r')) {
eol = true;
break charLoop;
}
}
startChar = nextChar;
nextChar = i;
if (eol) {
String str;
if (s == null) {
str = new String(cb, startChar, i - startChar);
} else {
s.append(cb, startChar, i - startChar);
str = s.toString();
}
nextChar++;
if (c == '\r') {
skipLF = true;
}
return str;
}
if (s == null)
s = new StringBuffer(defaultExpectedLineLength);
s.append(cb, startChar, i - startChar);
}
}
}
Note that this one receive a boolean, but calling readLine simply call this one with false passed, unless on Linux.
Notice the for(;;) loop, which is an infinite loop.
Try concatening to the "line" sent from the server
System.getProperty("line.separator");

Java - Writing a Method to Count Lines In a Text File Without Throwing Exceptions

Below is a solution from Number of lines in a file in Java
to quickly count the number of lines in a text file.
However, I am trying to write a method that will perform the same task without throwing an 'IOException'.
Under the original solution is my attempt to do this with a nested try-catch block <-- (Is this usually done/frowned upon/ or easily avoidable??) which returns 0 no matter how many lines are in the given file (obviously a fail).
Just to be clear, I am not looking for advice on how to better use the original method that does contain the exception and, therefore, the context within which I am using it is irrelevant to this question.
Can somebody please help me write a method that counts the number of lines in a text file and does not throw any exceptions? (In other words, deals with potential errors with a try-catch.)
Original line counter by martinus:
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}
My Attempt:
public int countLines(String fileName ) {
InputStream input = null;
try{
try{
input = new BufferedInputStream(new FileInputStream(fileName));
byte[] count = new byte[1024];
int lines = 0;
int forChar;
boolean empty = true;
while((forChar = input.read(count)) != -1){
empty = false;
for(int x = 0; x < forChar; x++){
if(count[x] == '\n'){
lines++;
}
}
}
return (!empty && lines == 0) ? 1 : lines + 1;
}
finally{
if(input != null)
input.close();
}
}
catch(IOException f){
int lines = 0;
return lines;
}
}
It is more robust to use char instead of byte for '\n' and return -1 in case of any errors, for example if the filename does not exist:
public static int countLines(String filename) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
char[] c = new char[1024];
int count = 0;
int readChars = 0;
boolean emptyLine = true;
while ((readChars = br.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
emptyLine = false;
if (c[i] == '\n') {
++count;
emptyLine = true;
}
}
}
return count + (!emptyLine ? 1 : 0);
} catch (IOException ex) {
return -1;
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
// Ignore intentionally
}
}
}
Sharing my attempt.
public static int countLines(String filename) {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
int numLines = 0;
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
numLines = (count == 0 && !empty) ? 1 : count;
} catch (IOException ex) {
numLines = 0;
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
numLines = 0;
} finally {
is.close();
}
return numLines;
}

I desperately need help for file input/output in java

I need help about inputting using file (file name is inp2.dat) and outputting using file (file name is out2.dat) in the SAME PROGRAM. Do I use FileInputStream and FileOutputStream in the same class? Please help. Its outputting File Not Found.
import java.io.*;
class MBF
{
static String fileinp="inp2.dat";
public void main()
{
boolean EOF=false;
try
{
FileInputStream fr=new FileInputStream(fileinp);
DataInputStream dr=new DataInputStream(fr);
while(!EOF)
{
try
{
System.out.println("Enter no. of inputs:");
int n=dr.readInt();
int max=0;
for(int a=1;a<=n;a++)
{
System.out.println("Enter:");
int p=dr.readInt();
String str=dr.readLine();
max=max+1;
if(str.charAt(1)==str.charAt(0))
max=max+1;
else
max=max+2;
for(int i=0;i<p-2;i++)
{
char f=str.charAt(i);
char s=str.charAt(i+1);
char t=str.charAt(i+2);
if((f==s)&&(f==t))
max=max+1;
else
if(((f==s)&&(f!=t))||((s==t)&&(f!=t))||((f==t)&&(t!=s)))
max=max+2;
else
max=max+3;
}
max=0;
}
}
catch(EOFException el)
{
System.out.println("end of file");
EOF=true;
}
catch(IOException e)
{
System.err.println(e);
}
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
}
}
There are a few problems throughout. I've made some changes with comments:
class MBF
{
static String fileinp = "C:\\inp2.dat";
public static void main(String[] args) // main method signature was wrong
{
// this line doesn't need to be outside of main, and you aren't using your fileinp string
Scanner in = new Scanner(new File(fileinp));
// added your writer
BufferedWriter out = new BufferedWriter(new FileWriter("C:\\out2.dat"));
System.out.println("Enter no. of inputs:");
int n = in.readInt();
//in.close(); I don't think you meant to do this here.
int max=0;
for(int a = 1; a <= n; a++)
{
System.out.println("Enter:");
// these were originally dr.read... dr is not a variable in scope here. I think you meant in
int p = in.readInt();
String str = in.readLine();
max=max+1;
if(str.charAt(1)==str.charAt(0))
max=max+1;
else
max=max+2;
for(int i = 0; i < p - 2; i++)
{
char f = str.charAt(i);
char s = str.charAt(i + 1);
char t = str.charAt(i + 2);
if ((f == s) && (f == t))
max=max+1;
else if (((f == s) && (f != t)) || ((s == t) && (f != t)) || ((f == t) && (t != s)))
max=max+2;
else
max=max+3;
}
out.write(max + "\n");
max=0;
}
in.close();
out.close();
}
}
Should do what you want.

Categories

Resources