如何读取文件,反转顺序,以及写入相反的顺序

问题描述 投票:2回答:5

就像我制作的类似项目一样,这个项目是从txt文件中读取字符,颠倒字符串的顺序并将其重写为另一个txt文件。但它一直在输出我的“出问题”的例外。任何人都可以帮我解决出错的问题吗?

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class ReverseFile
{
    public static void main(String[] args) throws IOException
       {
          try{
          String source = args[0];
          String target = args[1];

          File sourceFile=new File(source);

          Scanner content=new Scanner(sourceFile);
          PrintWriter pwriter =new PrintWriter(target);

          while(content.hasNextLine())
          {
             String s=content.nextLine();
             StringBuffer buffer = new StringBuffer(s);
             buffer=buffer.reverse();
             String rs=buffer.toString();
             pwriter.println(rs);
          }
          content.close();    
          pwriter.close();
          System.out.println("File is copied successful!");
          }

          catch(Exception e){
              System.out.println("Something went wrong");
          }
       }
}

所以这里是来自stacktrace的信息:

java.lang.ArrayIndexOutOfBoundsException: 0
    at ReverseFile.main(ReverseFile.java:36)
java file-io indexoutofboundsexception
5个回答
3
投票

我不太确定你的环境,文本可能有多长。我也不太确定你为什么需要扫描仪?

无论如何,这是我对问题的看法,希望这可以帮助你:)

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;


public class Reverse {

    public static void main(String[] args) {

        FileInputStream fis = null;
        RandomAccessFile raf = null;

        // by default, let's use utf-8
        String characterEncoding = "utf-8";

        // but if you pass an optional 3rd parameter, we use that
        if(args.length==3) {
            characterEncoding = args[2];
        }

        try{

            // input file
            File in = new File(args[0]);
            fis = new FileInputStream(in);

            // a reader, because it respects character encoding etc
            Reader r = new InputStreamReader(fis,characterEncoding);

            // an outputfile 
            File out = new File(args[1]);

            // and a random access file of the same size as the input, so we can write in reverse order 
            raf = new RandomAccessFile(out, "rw");
            raf.setLength(in.length());

            // a buffer for the chars we want to read 
            char[] buff = new char[1];

            // keep track of the current position (we're going backwards, so we start at the end)
            long position = in.length(); 

            // Reader.read will return -1 when it reached the end.
            while((r.read(buff))>-1) {

                // turn the character into bytes according to the character encoding
                Character c = buff[0];
                String s = c+"";
                byte[] bBuff = s.getBytes(characterEncoding);

                // go to the proper position in the random access file
                position = position-bBuff.length;
                raf.seek(position);

                // write one or more bytes for the character
                raf.write(bBuff);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // clean up
            try {
                fis.close();
            } catch (Exception e2) {
            }
            try {
                raf.close();
            } catch (Exception e2) {
            }
        }


    }


}

3
投票

您需要在运行程序时在命令行上指定文件名(源和目标)。

java ReverseFile source.txt target.txt

在您的程序中,您尝试从命令行中读取文件的名称

String source = args[0];
String target = args[1];

因此,如果你没有在那里指定那些名字,java会尝试访问索引0和1的数组args,这些数据为空,你得到ArrayIndexOutOfBoundsException


0
投票

这里是你的错误免费解决你的问题,你使用“扫描仪”而不导入“util”包。我们去:-----------

   import java.io.*;
    import java.util.*;

        public class ReverseFile
         {
         public static void main(String[] args) throws IOException
          {
      try{
      File sourceFile=new File(args[0]);
      Scanner content=new Scanner(sourceFile);
      PrintWriter pwriter =new PrintWriter(args[1]);

      while(content.hasNextLine())
      {
         String s=content.nextLine();
         StringBuffer buffer = new StringBuffer(s);
         buffer=buffer.reverse();
         String rs=buffer.toString();
         pwriter.println(rs);
      }
      content.close();    
      pwriter.close();
      System.out.println("File is copied successful!");
      }

      catch(Exception e){
          System.out.println("Something went wrong");
      }
   }
      }

0
投票

只想到一个简单的方法。

public class ReadFileReverse {

public int[] readByte(File _file) throws IOException {
    FileInputStream source = new FileInputStream(_file);
    int currentByte = source.available();
    int readCount = 0;

    int byteContainer[] = new int[currentByte];
    while(readCount < currentByte){
        byteContainer[readCount] = source.read();
        readCount++;
    }
    source.close();
    return byteContainer;
}

public void printReverse(int[] fileContent){
    for(int byt=fileContent.length -1; byt >= 0 ; byt--){
        System.out.print((char) fileContent[byt]);
    }
}

public static void main(String[] args) throws IOException {
    File fileToRead = new File("/README.txt");

    ReadFileReverse demo = new ReadFileReverse ();
    int[] readBytes = demo.readByte(fileToRead);

    demo.printReverse(readBytes);
}

}

0
投票

这里我们正在读取字符串变量中的文件,然后使String Builder对象有效地执行反向操作,然后打印

package com;

import java.io.FileReader;

public class Main {
	public static void main(String[] args) {

		try {
			FileReader fr = new FileReader("D:\\newfile.txt");
			String str = "";
			int ch;
            //reading characters in to string variable
			while ((ch = fr.read()) != -1) {
				str += Character.toString((char) ch);
			}
			System.out.println("Original String : " + str);
            //converting string variable to String Builder object
			StringBuilder sb = new StringBuilder(str);
            //reversing the string and printing
			System.out.println("Reverse order : " + sb.reverse());
			fr.close();
		} catch (Exception e) {
			System.out.println("error");
		}
	}
}

输出:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.