Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

How to pass int to a file

Posted on 2003-03-21
9
Medium Priority
?
250 Views
Last Modified: 2010-03-31
Hello,
  I am a beginner in java. I want to create an integer array in a java program and write the integers into a flat file(notepad). I have come accross only methods which write characters and Strings to a flat file. If I want to write inegers, some characters are displayed. Please give me the code to make it work.
Thanks
0
Comment
Question by:svraju
8 Comments
 
LVL 4

Expert Comment

by:kokchoon78
ID: 8179895
Hi,

  try this :

File outputFile = new File( "C:\myOut.txt" );
int intArray[] = {1,2,3,4,5};

PrintWriter pw = new PrintWriter( new FileWriter( uotputFile ) );

for ( int i = 0; i < intArray.length; i ++ )
{
   pw.println( intArray[i] );  
}
pw.flush();
pw.close();



regards,
Kok Choon.
0
 

Expert Comment

by:markbrdsly
ID: 8179908
Hi

You need to use the DataOutputStream class. That class contains a method called writeInt() that DOES allow you to write a primitive int value to a file.

Do something like the following;

1. Open an OutputStream to the file - a FileOutputStream for instance;

FileOutputStream fos = new FileOutputStream("C:\\WINDOWS\\Desktop\\outfile.txt");

2. Chain that into the constructor of the DataOutputStream class;

DataOutputStream dos = new DataOutputStream(fos);

3. Then call the writeInt() method of the DataOutputStream object to write to the file;

int i = 25;
dos.writeInt(i);

Of course, you will need to flush and close the file at the end of the output, and provide catch clauses to handle any exceptions that may get thrown. Try something along these lines;

FileOutputStream fos = null;
DataOutputStream dos = null;
int[] intArray = {25, 35, 45, 55, 65, 75}

try
{
   fos = new FileOutputStream("C:\\WINDOWS\\Desktop\\outfile.txt");
   dos = new DataOutputStream(fos);
   for(i = 0; i < intArray.length; i++)
   {
      dos.writeInt(intArray[i]);
   }
}
catch(Exception e)
{
   // Deal with any exceptions in here.
   // Use the more specific Exception subclasses
   // you will find in the documentation - Exception
   // itself is FAR too wide.
}
finally
{
   try
   {
      if(dos != null)
      {
         dos.flush();
         dos.close();
      }
   }
   catch(Exception e)
   {
   }
}
0
 
LVL 3

Expert Comment

by:popa_duhu
ID: 8180307
Hi.
Try this:

import java.io.*;

public class Test {
 public static void main(String args[]){
   int[] intArray = new int[]{1,2,3,4,5};
   PrintWriter out = new PrintWriter(new FileOutputStream("a.txt"));
   for(int i=0; i<intAray.length; i++){
        out.println(intArray[i]);
   }
   out.flush();
   out.close();

 }

}
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 3

Expert Comment

by:popa_duhu
ID: 8180340
Hi. i've made a little mistake in my previous sample.

try this one:

import java.io.*;

public class Test throws Exception{
 public static void main(String args[]){
   int[] intArray = new int[]{1,2,3,4,5};
   PrintWriter out = new PrintWriter(new FileOutputStream("a.txt"));
   for(int i=0; i<intAray.length; i++){
        out.println(intArray[i]);
   }
   out.flush();
   out.close();
 }
}

best regards,
popa_duhu
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 80 total points
ID: 8180385
That would leave you with a file that's unreadable by Notepad, as it would be in 'binary' format. It should be as follows:

import java.io.*;

public class Test throws Exception{
public static void main(String args[]){
  int[] intArray = new int[]{1,2,3,4,5};
  PrintWriter out = new PrintWriter(new FileOutputStream("a.txt"));
  for(int i=0; i<intAray.length; i++){
       out.println(Integer.toString(intArray[i]));
  }
  out.flush();
  out.close();
}
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8180401
and exceptions should be caught ;-)

public class Test throws Exception{
  public static void main(String args[]){
    try {
      int[] intArray = new int[]{1,2,3,4,5};
      PrintWriter out = new PrintWriter(new FileOutputStream("a.txt"));
      for(int i=0; i<intAray.length; i++){
        out.println(Integer.toString(intArray[i]));
      }
      out.flush();
      out.close();  
    }
    catch(Exception e){
      e.printStackTrace();
    }  
  }
}
0
 

Expert Comment

by:CleanupPing
ID: 9058562
svraju:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9730600
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

Accept CEHJ's comment as answer.

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

jimmack
EE Cleanup Volunteer
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses
Course of the Month11 days, 18 hours left to enroll

564 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question