?
Solved

How to pass int to a file

Posted on 2003-03-21
9
Medium Priority
?
248 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 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
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 
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

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!

Question has a verified solution.

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

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
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…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month13 days, 16 hours left to enroll

801 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