The code below is supposed to create and write to a file, but it doesn't create a file in my directory. Everything with the Scanner is working, it scans everything from jTextField perfectly.
OutputStream os;
try {
os = new FileOutputStream("kurinys.dat");
try (DataOutputStream dos = new DataOutputStream(os)) {
Scanner skanuoklisSaugojimui = new Scanner(jTextField1.getText());
while(skanuoklisSaugojimui.hasNextInt()){
int natosAukstis = skanuoklisSaugojimui.nextInt();
dos.writeInt(natosAukstis);
}
}
os.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Grafika.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Grafika.class.getName()).log(Level.SEVERE, null, ex);
}
Can someone please help me find the problem?
Don't use a nested try, it doesnt have any sense and could case a lot of problems in terms of exception handling.
OutputStream os;
try {
os = new FileOutputStream("kurinys.dat");
}
catch (FileNotFoundException e) {
}
try (DataOutputStream dos = new DataOutputStream(os)) {
Scanner skanuoklisSaugojimui = new Scanner(jTextField1.getText());
while(skanuoklisSaugojimui.hasNextInt()){
int natosAukstis = skanuoklisSaugojimui.nextInt();
dos.writeInt(natosAukstis);
}
}
os.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Grafika.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Grafika.class.getName()).log(Level.SEVERE, null, ex);
}
Related
I created an application with TCP, it works nice when I used it on a local network with 127.0.0.1 but the server refused to works when a client try to connect to him from an another network.
I don't know what this error means and how to resolve it and I can't anderstand that an application could works only on LAN.
public class Reception {
InputStream inObjet = null;
BufferedReader inString = null;
ObjectInputStream recVec2i = null;
public Reception(Socket socket) {
try {
this.inObjet = socket.getInputStream();
this.inString = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.recVec2i = new ObjectInputStream(inObjet);
} catch (IOException ex) {
Logger.getLogger(Reception.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Vecteur2i recevoir() {
Vecteur2i to = new Vecteur2i();
try {
to = (Vecteur2i) recVec2i.readObject();
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(Reception.class.getName()).log(Level.SEVERE, null, ex);
to = new Vecteur2i(1000, 1000);
}
return to;
}
public String recevoirString() {
String chaine = "";
try {
chaine = inString.readLine();
} catch (IOException ex) {
Logger.getLogger(Reception.class.getName()).log(Level.SEVERE, null, ex);
}
return chaine;
}
public void fermerReception() {
try {
inString.close();
} catch (IOException ex) {
Logger.getLogger(Reception.class.getName()).log(Level.SEVERE, null, ex);
}
try {
inObjet.close();
} catch (IOException ex) {
Logger.getLogger(Emission.class.getName()).log(Level.SEVERE, null, ex);
}
try {
recVec2i.close();
} catch (IOException ex) {
Logger.getLogger(Reception.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And here the exception :
avr. 22, 2015 9:33:33 PM Snake.Reception recevoir Grave: null
java.io.EOFException at
java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2597)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1316)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at Snake.Reception.recevoir(Reception.java:41) at
Snake.Partie.cycleDeJeu(Partie.java:55)
Regards,
You can't mix different types of stream via the same socket when one or more of them is buffered, and both BufferedInputStream and ObjectInputStream are buffered. The buffers will 'steal' data from each other. In your case you should do all the I/O via the object stream. It has String-based methods.
String path=this.getClass().getResource("info.txt").toString();
void writeinfo()
{
PrintWriter writer = null;
try {
writer = new PrintWriter(path);
writer.println(highscore);
for(int i=1;i<=30;i++)
{
for(int j=1;j<=30;j++)
{
writer.println(v[i][j]);
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
writer.close();
}
}
i just pasted the relevant part of the code. It says "java.io.FileNotFoundException", but the file does exist! I searched online but i find no solution to this.
I'm having problems with appending a generic object within an existing file. This method is supposed to append the object to the existing file if the parameters are "true" and overwrites the entire file if "false". The "false" statement works perfectly fine, it overwrites the entire file but I can't seem to get the append one to work. It seems to do nothing at first glance but when I placed a simple System.out.println("test"); in the while (true) loop, it runs forever. How can I fix this?
public <T> void writeOneObject(T type, boolean append) throws NotSerializableException{
if (append == true){
//TODO
if (file.exists ()){
ObjectOutputStream ois = null;
try{
ois = new ObjectOutputStream (new FileOutputStream (file, true));
while (true){
ois.writeObject(type);
}
}catch (StreamCorruptedException e){
}catch (EOFException e){
}catch (Exception e){
e.printStackTrace ();
}finally{
try{
if (ois != null) ois.close();
}catch (StreamCorruptedException e){
}catch (IOException e){
e.printStackTrace ();
}
}
}
}
else { //overwrites the entire file
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(type);
oos.flush();
oos.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (StreamCorruptedException e) {
System.out.println("error");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I also have this inside the class:
class NoHeaderObjectOutputStream extends ObjectOutputStream {
public NoHeaderObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
protected void writeStreamHeader() {}
}
I have following code :
// Read properties file.
Properties properties = new Properties();
try {
properties.load(new FileInputStream("filename.properties"));
} catch (FileNotFoundException e) {
system.out.println("FileNotFound");
}catch (IOException e) {
system.out.println("IOEXCeption");
}
Is it required to close the FileInputStream? If yes, how do I do that? I am getting a bad practice error in my code checklist . Asking it to put finally block.
You must the close the FileInputStream, as the Properties instance will not. From the Properties.load() javadoc:
The specified stream remains open after this method returns.
Store the FileInputStream in a separate variable, declared outside of the try and add a finally block that closes the FileInputStream if it was opened:
Properties properties = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream("filename.properties");
properties.load(fis);
} catch (FileNotFoundException e) {
system.out.println("FileNotFound");
} catch (IOException e) {
system.out.println("IOEXCeption");
} finally {
if (null != fis)
{
try
{
fis.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Use try-with-resources since Java 7:
final Properties properties = new Properties();
try (final FileInputStream fis =
new FileInputStream("filename.properties"))
{
properties.load(fis);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOEXCeption: " + e.getMessage());
}
You should always close your streams, and doing it in the finally block is a good practice. The reason for this is that the finally block always gets executed, and you want to make sure that the stream is always closed, even if Something Bad happens.
FileInputStream inStream = null;
try {
inStream = new FileInputStream("filename.properties");
properties.load(inStream);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
} catch (IOException e) {
System.out.println("IOEXCeption");
} finally {
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If you are using Java 7, this becomes much easier, since a new try-with syntax was introduced. Then you can write like this:
try(FileInputStream inStream = new FileInputStream("filename.properties")){
properties.load(inStream);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
} catch (IOException e) {
System.out.println("IOEXCeption");
}
and the stream is closed automatically.
here is an example:
public class PropertiesHelper {
public static Properties loadFromFile(String file) throws IOException {
Properties properties = new Properties();
FileInputStream stream = new FileInputStream(file);
try {
properties.load(stream);
} finally {
stream.close();
}
return properties;
}
}
You can use Lombok #Cleanup to do it simply.
http://projectlombok.org/features/Cleanup.html
Properties properties = new Properties();
try {
#Cleanup FileInputStream myFis = new FileInputStream("filename.properties");
properties.load(myFis);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
}catch (IOException e) {
System.out.println("IOEXCeption");
}
Or, only if your are using Java 7, there is the "try with resource" new feature.
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Properties properties = new Properties();
try (FileInputStream myFis = new FileInputStream("filename.properties")) {
properties.load(myFis);
} catch (FileNotFoundException e) {
System.out.println("FileNotFound");
}catch (IOException e) {
System.out.println("IOEXCeption");
}
I found a question here on SO: Convert ArrayList<String> to byte []
It is about converting ArrayList<String> to byte[].
Now is it possible to convert byte[] to ArrayList<String> ?
Looks like nobody read the original question :)
If you used the method from the first answer to serialize each string separately, doing exactly the opposite will yield the required result:
ByteArrayInputStream bais = new ByteArrayInputStream(byte[] yourData);
ObjectInputStream ois = new ObjectInputStream(bais);
ArrayList<String> al = new ArrayList<String>();
try {
Object obj = null;
while ((obj = ois.readObject()) != null) {
al.add((String) obj);
}
} catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectInputStream
try {
if (ois != null) {
ois.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
If your byte[] contains the ArrayList itself, you can do:
ByteArrayInputStream bais = new ByteArrayInputStream(byte[] yourData);
ObjectInputStream ois = new ObjectInputStream(bais);
try {
ArrayList<String> arrayList = ( ArrayList<String>) ois.readObject();
ois.close();
} catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectInputStream
try {
if (ois!= null) {
ois.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Something like this should suffice, forgive any compile typos I've just rattled it out here:
for(int i = 0; i < allbytes.length; i++)
{
String str = new String(allbytes[i]);
myarraylist.add(str);
}
yeah its possible, take each item from byte array and convert to string, then add to arraylist
String str = new String(byte[i]);
arraylist.add(str);
it depends very much on the semantics you expect from such a method. The easiest way would be, new String(bytes, "US-ASCII")—and then split it into the details you want.
There are obviously some problems:
How can we be sure it's "US-ASCII" and not "UTF8" or, say, "Cp1251"?
What is the string delimiter?
What if we want one of the strings to contain a delimiter?
And so on and so forth. But the easiest way is indeed to call String constructor—it'll be enough to get you started.