Help with input output .txt files!

Hi i'm a student and totally new to programming. I need the program to read a .txt file and then output it:
import java.io.*;
import java.util.*;
public class Reading{
     public static void main(String[] args)throws Exception{
          Scanner scanner = new Scanner(new File(args[0]));
          while(scanner.hasNext()){
               System.out.println(scanner.next());
          scanner.close();
and
import java.io.*;
public class Writing{
     public static void main(String[] args)throws Exception{
          String outputFile = args[0];
          PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
          for(int i = 0; i < 100; i++){
               writer.println(i * i);
          writer.close();
How would i merge these together? I also changed the command line to java Reading Input.txt but it wont run on DrJava on my computer or laptop and i get an error? How do i then store the strings into an arraylist and iterate throught the arraylist to reverse the strings?
Please help.

You could do this...
import java.io.*;
import java.util.*;
public class FileIO2
     public static void main(String argsp[])
          String readfile="ajr.txt";
          String writefile="ajr2.txt";
          try{
          read(readfile);
          write(writefile);
          catch(Exception e)
          {e.printStackTrace();}
     public static void read(String filename) throws Exception
          Scanner scanner = new Scanner(new File(filename));
          while(scanner.hasNext()){
               System.out.println(scanner.next());
          scanner.close();
     public static void write(String filename) throws Exception
          String outputFile = filename;
          PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
          for(int i = 0; i < 100; i++){
               writer.println(i * i);
          writer.close();
}

Similar Messages

  • Help with Input Output error

    I am learning java and when I got to input output (the sample program is a BMI calculator) in my book i had to stop because i got a weird error.
    Error:
    BMICalculator.java:17 cannot find symbol
    symbol : method create(java.io.InputStream)
    location : class java.util.Scanner
    Scanner stdin = Scanner.create(System.in);
    ^
    And the line it has a problem with:
    Scanner stdin = Scanner.create(System.in);
    I would appreciate any help.

    impot java.util.*;
    public class BMICalculator {
    public static void main(String[]args) {
    final double KILOGRAMS_PER_POUND = 0.454;
    final double METERS_PER_FOOT = 0.3046;
    System.out.println("BMI Calculator\n");
    //Line it has a problem with
    Scanner stdin = Scanner.create(System.in);
    System.out.print("Enterweight (lbs): ");
    double weight = stdin.nextDouble();
    System.out.print("Enter height (feet); );
    double height = stdin.nextDouble();
    double metricWeight= weight * KILOGRAMS_PER_POUND;
    double metricHeight = height * METERS_PER_FOOT;
    double bmi = metricWeight / (metricHeight * metricHeight);
    System.out.println("A person with");
    System.out.println(" weight " + witght + " (lbs) ");
    System.out.println(" height " + height + " (feet) ");
    System.out.println("has a BMI of " + Math.round(bmi));
    }

  • Help with Input/Output Parameter Size using OLE DB Provider

    I am using the OLE DB Provider for 9i in an Active Server Page to call a stored procedure in a 9i database. I pass have an input/output parameter (adVarChar with adSize=30) in which I pass a two digit number in, and expect to get a character value greater than 2 characters in return. However, when I execute the stored procedure call, it appears the value being returned in the parameter is being truncated to the size of the value I passed in (2 characters). Is there a way I can insure the parameter will return the entire length of the result regardless of the length of the input value?

    cmd.Parameters.Add("retstatus", OracleDbType.Varchar2, 200, ParameterDirection.InputOutput); It seems to me that you're trying to use an OracleParameter constructor with parameter name, parameter type, parameter SIZE, and parameter direction. But OracleParameter class does not have any such constructor. Therefore, your test tries to use another constructor incorrectly.
    OracleParameter has two constructors with four parameter ...
    public OracleParameter(string parameterName, OracleDbType type, object obj, ParameterDirection direction)
    public OracleParameter(string parameterName, OracleDbType type, int size, string srcColumn)
    ... and none of these matches your constructor. One way to solve this problem is to use appropriate constructor or OracleParameter properties.

  • Help with inputting from text file.

    Okay, been struggling with this for a couple days and I could really use some help.
    I need to input text one line at a time into String[] text, I'm reading from a file called "textfile.txt" and I want to store the result
    String[] text = { first_line, second_line, third_line, fourth_line...........etc}
    This works now:
    //code
    String[] test =
         { "1 2, 3 4, 5 6"
         for (int i = 0; i < test.length; i++) {
         Graph g = new Graph(test);
    // end code
    But that of course reads "1 2, 3 4, 5 6" from the code, and not from a text file. My StringTokenizer looks for a "," and makes that the end of the token, so I need to add a "," after each line as well.
    In other words, I need to turn the text file :
    "1 2
    3 4
    5 6"
    into :
    "1 2, 3 4, 5 6"
    These are just numbers to test of course, the real text file I need to input has hundreds of lines.
    Any help would be appreciated, thank you.

    I'm fairly lost. I understand that you need to read a file, and that file contains many lines which each contain a pair of numbers. But then you say (a) that you need to create an array of Strings and (b) that you need to store the result. And there's this mysterious StringTokenizer in there as well. You seem to be suggesting some solution that concatenates all the lines together, with commas between them, so that the StringTokenizer can then go through that concatenation and break it apart into the original pieces.
    Okay, here's some code that reads through a file and makes an array of Strings, one entry per line:BufferedReader in = new BufferedReader(new FileReader("textfile.txt"));
    String data = null;
    List inputs = new ArrayList();
    while ((data = in.readLine()) != null) {
      inputs.add(data);
    in.close();
    String[] lines = new String[0];
    lines = (String[]) inputs.toArray(lines);Untested, and exception handling and so forth omitted. I leave it to you to decide what to do with that array of Strings.
    PC&#178;

  • Help with printing a txt file

    Hi, Im having some (a lot) of trouble getting my head round how to actually print a text file.
    Literally i want no formatting, no user interaction or anything, it just has to print a text file, im looking to create a method that is called by another method.
    I know everyone says read the API, however im really not finding it helpfull at all, so if anyone could give me a basic example, or just somewhere to start i'd be really gratefull.
    Thanks
    Alan

    If you are using Java J2SE 6 (which I would recommend unless you have a good reason not too) then it is
    as simple as this.
    import java.awt.Desktop;
    import java.io.File;
    public class Printer {
         public static void main(String[] args) throws Exception {
              Desktop.getDesktop.print(new File("c:\\test.txt"));
    }http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/
    http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#print(java.io.File)

  • I had a problem with the hard disk on a 2010 macbook pro. Replaced the hard disk with an Hitachi 1TB and when I tried to erase and format It fails with input/output error. Any help much appreciated!

    I had a problem with the hard disk on a 13" 2010 macbook pro. Replaced the hard disk with an Hitachi 1TB disk but when I tried to erase and format, it fails with input/output error and at other times saying unable to allocate memory. Any help much appreciated!

    Zap the PRAM and Reset the SMC, then try again.

  • File with list of .txt files in a specific directory

    Hi,
    I need to create a file with list of .txt files in a specific directory (actually the command will be used by a java application).
    I am using the below command,
    ls home/apptmt/park/*.txt > home/apptmt/park/reportgen.txt
    but this command prints output as
    home/apptmt/park/report1.txt
    home/apptmt/park/report2.txt
    home/apptmt/park/report3.txt
    I need only the files in reportgen.txt file, like
    report1.txt
    report2.txt
    report3.txt
    any one help me on the command I should use to get this output?
    Thanks
    MT

    Thank you Dude!
    I just found out that
    cd /home/apptmt/park;ls *.txt > reportgen.lst works for me...
    I will try this one as well... thank you very much...
    MT

  • Want to display a space after last field in the output txt file

    hi
    I want to display a space after last field in the output txt file which is generaed by my program on utility server the last field lengyt we have defined is four and in database it is of three characters and requirement is to disppaly the last fourth field as space in the output file w hich is not shown as the txt file automatically gets closed at the third place as it is the last field in the record and ind atabase records are of therss char only but user wants to display this fourth position in the notepad output file as space ( which is last field in the output file)
    eg
    name house  street country
    record output coming in file
    ram   h3      street3  thn      now this thn which is last field the notepad get closed at thn only
    i want to display one space in last field for the whole of output file
    ie ram      h3   street3  thn(space)
        sham   h4  street4   sgp(space)  so on......
    we need to show this space in the output file as blank
    regards
    Arora

    hi Atish
    i am using
    loop at gt_sagadr_outtab into wa_sagadr_outtab
    move wa_sagadr_outtab-country to wa_sagadr_text+223(226).
    endloop
    in this last field ie country i need to display the last 226 as blank as only country key is two char in database so the last space is not shown
    i am not unsing the fM as tolb by  you
    and afterwards
    i am usning
    Concatenate 'Sagadr_' sy-datum sy-uzeit '.dat' into gv_filename_sagadr.
    CALL FUNCTION 'FILE_GET_NAME'
      EXPORTING
      CLIENT                        = SY-MANDT
        LOGICAL_FILENAME              = gc_lfile
        OPERATING_SYSTEM              = SY-OPSYS
        PARAMETER_1                   = gc_param1
        PARAMETER_2                   = gc_send
        PARAMETER_3                   = gv_filename_sagadr
      USE_PRESENTATION_SERVER       = ' '
      WITH_FILE_EXTENSION           = ' '
      USE_BUFFER                    = ' '
      ELEMINATE_BLANKS              = 'X'
      IMPORTING
      EMERGENCY_FLAG                =
      FILE_FORMAT                   =
        FILE_NAME                     =  gv_filepath_sagadr
    EXCEPTIONS
      FILE_NOT_FOUND                = 1
      OTHERS                        = 2
    IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
             WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    and lastly
    open dataset gv_filepath_sagadr for output in text mode encoding default.
        if sy-subrc eq 0.
         loop at gt_sagadr_text into wa_sagadr_text.
         transfer wa_sagadr_text to gv_filepath_sagadr.
         endloop.
        endif.
       close dataset gv_filepath_sagadr.
        if sy-subrc = 0.
        message S002 with gv_filepath_sagadr. "Files & created on Application server
        endif.
    SO NOT SURE WHERE TO USE THE CODE AND HOW

  • Java.sql.SQLException: File input/output error: File input/output error: re

    Hi,
    We are using JCAPS 512. We use oracle eway to connect to Oracle 10g database. But sometimes we are getting the following exception
    and suddenly all jcds stop processing. If we restart the server again job continue processing, otherwise server hangs and nothing get processed.
    Exception is as follows
    java.sql.SQLException: File input/output error: File input/output error: reading: java.io.EOFException in statement [SET TABLE EVENT_STORE INDEX '11183416 55935']
         at org.hsqldb.Trace.getError(Unknown Source)
         at org.hsqldb.Log.runScript(Unknown Source)
         at org.hsqldb.Log.open(Unknown Source)
         at org.hsqldb.Database$Logger.openLog(Unknown Source)
         at org.hsqldb.Database.open(Unknown Source)
         at org.hsqldb.Database.<init>(Unknown Source)
         at org.hsqldb.jdbcConnection.openStandalone(Unknown Source)
         at org.hsqldb.jdbcConnection.<init>(Unknown Source)
         at org.hsqldb.jdbcDriver.connect(Unknown Source)
         at java.sql.DriverManager.getConnection(DriverManager.java:525)
         at java.sql.DriverManager.getConnection(DriverManager.java:171)
         at com.stc.eventmanagement.impl.DBEventStore$EventStoreDB.addNewConnection(DBEventStore.java:359)
         at com.stc.eventmanagement.impl.DBEventStore$EventStoreDB.getConnection(DBEventStore.java:444)
         at com.stc.eventmanagement.impl.DBEventStore$EventStoreDB.executeParameterizedQuery(DBEventStore.java:777)
         at com.stc.eventmanagement.impl.DBEventStore$EventStoreDB.access$000(DBEventStore.java:250)
         at com.stc.eventmanagement.impl.DBEventStore.getEventIDsList(DBEventStore.java:133)
         at com.stc.eventmanagement.impl.DBEventStore.getEventIDsList(DBEventStore.java:115)
         at com.stc.eventmanagement.impl.EventForwarderMBean.cachePersistedEvents(EventForwarderMBean.java:728)
         at com.stc.eventmanagement.impl.EventForwarderMBean.setup(EventForwarderMBean.java:334)
         at com.stc.eventmanagement.impl.EventForwarderMBean.invoke(EventForwarderMBean.java:565)
         at com.sun.jmx.mbeanserver.DynamicMetaDataImpl.invoke(DynamicMetaDataImpl.java:213)
         at com.sun.jmx.mbeanserver.MetaDataImpl.invoke(MetaDataImpl.java:220)
         at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:815)
         at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:784)
         at com.stc.eventmanagement.impl.EventManagementService.setupEventForwarderMbean(EventManagementService.java:270)
         at com.stc.eventmanagement.impl.EventManagementService.registerMBean(EventManagementService.java:147)
         at com.stc.eventmanagement.impl.EventManagementService.startService(EventManagementService.java:96)
         at com.stc.eventmanagement.impl.EventManagementResourceAdapter.start(EventManagementResourceAdapter.java:75)
         at com.sun.enterprise.connectors.ActiveInboundResourceAdapter.<init>(ActiveInboundResourceAdapter.java:94)
         at com.sun.enterprise.connectors.ActiveRAFactory.createActiveResourceAdapter(ActiveRAFactory.java:74)
         at com.sun.enterprise.connectors.ResourceAdapterAdminServiceImpl.createActiveResourceAdapter(ResourceAdapterAdminServiceImpl.java:269)
         at com.sun.enterprise.connectors.ResourceAdapterAdminServiceImpl.createActiveResourceAdapter(ResourceAdapterAdminServiceImpl.java:372)
         at com.sun.enterprise.connectors.ConnectorRuntime.createActiveResourceAdapter(ConnectorRuntime.java:204)
         at com.sun.enterprise.server.ConnectorModuleLoader.load(ConnectorModuleLoader.java:87)
         at com.sun.enterprise.server.ConnectorModuleLoader.load(ConnectorModuleLoader.java:108)
         at com.sun.enterprise.server.AbstractManager.load(AbstractManager.java:216)
         at com.sun.enterprise.server.AbstractManager.load(AbstractManager.java:106)
         at com.sun.enterprise.server.ApplicationLifecycle.onStartup(ApplicationLifecycle.java:183)
         at com.sun.enterprise.server.ApplicationServer.onStartup(ApplicationServer.java:295)
         at com.sun.enterprise.server.PEMain.run(PEMain.java:238)
         at com.sun.enterprise.server.PEMain.main(PEMain.java:186)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at org.apache.commons.launcher.ChildMain.run(ChildMain.java:269)
    |#]
    Please provide some suggestions to overcome this  error
    Regards
    Venkatesh.S

    Delete the EventStoreDb.data file (its somewhere in your logical host) and restart the logical host.

  • Problem with RTPExport output video files

    Hi, I have a problem with RTPExport output video files. One side streams H263/RTP(AVTransmit2.java) and other write this steam to a file by RTPExport.java. When network conditions are ideal, output video file has same fps and same number of frames like original file. Problem occures, when theres packet lost in network, then output file has different fps,and also has less frames like original video(because it didnt write missing frames to file, and thats why it get shorter). Pls how can I achieve output file that will have the same fps like original one? How to write to file an identical copy of what I can see while receiveing video with AVReceive2.java? Its there a way to modifi rtpexport or avreceiver to do this? Thanks a lot!

    Trubka wrote:
    When network conditions are ideal, output video file has same fps and same number of frames like original file. Problem occures, when theres packet lost in network, then output file has different fps,and also has less frames like original video(because it didnt write missing frames to file, and thats why it get shorter). Okay, first off, the second file is smaller on purpose. RTP intentionally drops packets that are old/out of order in order to make sure real-time video stays as close to real time as it can. This is by design, so there's really nothing that can be done about it.
    How to write to file an identical copy of what I can see while receiveing video with AVReceive2.java? Technically speaking, what you're getting in the RTPExport is exactly what you got on the receiving end. Any frames that are dropped during transmission will not be seen by the receiver, nor saved by the receiver.
    Pls how can I achieve output file that will have the same fps like original one? I'm not 100% sure that you can, but, you can give the following idea a try. I make no guarentees that it'll work, but it should work for you...
    [http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/solutions/RTPConnector.html]
    That example is an example of a "custom transport layer" for RTP connections. Essentially, it's some code that's handed the RTP packets on the transmission end, and it's expected to deliver those RTP packets on the other end. And it doesn't care about how they get from A to B, only that they do.
    If you were to replace the UDP socket in that example with a TCP socket, you would be guarenteed not to drop packets due to network reasons. Every RTP packet you were handed by the transmitter, you would then hand to the receiver. There is no guarentee that none of the packets would be cast away as "old" by the RTP protocol itself, but there's also no guarentee any of them would be. It's a crap-shoot at best, but it's certainly worth a try.

  • Why when I open the output.txt file, is strange code there, not 3.1

    i almost copy the example from "think in java book" chapter 11
    however, the result "output.txt file" when opened by notepad of windows xp, always only very strange code inside, not what i want
    do i need open the file, before i want to write?
    or i use a wrong api again?
    or the java code norm is very difference from ms windows?
    thanks
    import java.util.Random;
    import java.io.*;
    class CreatRandomFile
         public static void main(String args[])throws IOException
              File fileOutput=new File("output.txt");
              DataOutputStream out2=
                   new DataOutputStream(
                        new BufferedOutputStream(
                             new FileOutputStream(fileOutput)));
              out2.writeDouble(3.1);
              out2.close();
         }//end main
    }//end class

    There are basically two ways of IO:
    a) human readable format;
    b) machine readable format;
    What you've just done is writing a double value in machine readable
    format to a file. Some folks call it 'binary format'. I bet your file is eight
    byes long. A DataOutputStream writes data in machine readable
    format. You need a PrintStream instead if you (a being human I suppose)
    want to be able to read the contents of that file.
    kind regards,
    Jos

  • Help with converting a Nero file

    I have previously converted a dvd insert designed with Nero into a pdf using adobe acrobat in order to send to someone else.  When I tried to do the same thing today with a new Nero designed insert the conversion wouldn't work.  The message said adobe didn't support the program that created the file.  Any ideas?

    thanks for your response.
    When I create a dvd insert or cd label etc using Nero the file extension is nct - nero cover template.  The printer wants the file as a pdf as he can't open Nero files.  I have version 9.3 of acrobat.
    Date: Mon, 18 Jan 2010 21:43:47 -0700
    From: [email protected]
    To: [email protected]
    Subject: help with converting a Nero file
    Nero is simply a CD/DVD burning application and should have no effect on the type of files that will eventually be on the CD/DVD.
    What type of files are you trying to convert and exactly how are you trying to convert them? Plus, it would help to know the version of Acrobat you are using.
    >

  • I had to put my computer by together without migration or time machine I NEED help with order of the files?

    I had to put my computer by together without migration or time machine I NEED help with order of the files?

    Hi, where are these other files exactly?

  • Help with DIgital Output Array with 6062E DAQ CARD...

    Good morning, folks... I need some help with digital output of the 6062E PCMCIA card... I can output 1 line without problems... I need to control a 4066 with my digital outputs... I am doing this without greater problems... but there's something... I need that when one of my outputs is high, the others become low, unchangeably... so I tried to use an array to control my output and I couldn't do that... some errors showed up... can you help me please? Maybe there's any errors at my software, then I thank you if you help me... the vi is anexed...
    Best Regards...
    Attachments:
    Untitled 3.vi ‏20 KB

    See below for one of many methods. Change the "lines" string for your setup.
    Also, please explore the Examples that ship with LabVIEW, and read your card's manual.
    Richard

  • Disk Utility: Create image fails with input/output error

    Starting to create an image and saving it into an external hard drive (MacOS extended Journaled).
    It starts after less than 60 secs it comes out with an error : Failed to create the image (input/output error)

    If you don't mind I'd like to discourage you from backing up a drive onto a disc image file no matter where you plan to save it. Disc image files can be very problematical when it comes to trying to restore the backup. Furthermore, you cannot boot from a disc image. If the disc image file becomes corrupted then you have no backup.
    I would like to propose that you think about a better way to backup your drive. You can clone the drive to your backup drive. It's easy to do using Disk Utility's Restore feature. A clone backup is not only bootable but you have direct access to all the files on the backup.
    In order to make a bootable clone open Disk Utility. Select Disk Utility Help from the Help menu. Search for +duplicating a disk+. Click on "Duplicating a disk" at the top of the list of articles. Follow the directions.

Maybe you are looking for

  • Simple Email Campaign - Extracting reports

    Hi everyone, I have a simple email campaign running (still active) and I am wondering how you can export the clicks, opens of this campaign. I can't see it in Insights as a campaign and there's nothing in the settings apart from campaign audit, entry

  • Syntax Check for *.java files

    Hello erveryone, I'm wondering if anybody has an advice how to enable (if possible) syntax check in JDeveloper 10.1.2. For example: public String toString() { String result = "test"; The missing return statement is not shown in the editor. It's only

  • Authorization object to lock the SOLAR 02 config structure

    hi guys , does anyone know of a authorization object which can help lock the configuration structure in SOLAR02, Users should be able to change the structure ,rename it etc  but they shouldnt be able to delete any nodes in the Config Structure . Rega

  • Slow Perforamnce while executing the customizing program

    HI All My Prd server hardware are consist of 2 itanium processor, 8gb ram and 20gb pagefile with the 500 GB SAN Storage for the datadisk. I have almost 250 users on my PRD server over the 8 branches with the WAN connectivity. I have been set the 15 w

  • How do I open RW2 files in PSE and LR 5.3?

    My new Panasonic DMC-TZ61 produces raw images with ending "RW2". Eiher Elemenst 12 nor Lightroom 5.3 open these files. Who can help me with that problem?