gpt4 book ai didi

java - 如何读取文件、反转顺序和反转顺序写入

转载 作者:行者123 更新时间:2023-12-02 09:37:43 25 4
gpt4 key购买 nike

就像我做的一个类似的项目一样,这个项目是从一个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");
}
}
}

这是来自堆栈跟踪的信息:

java.lang.ArrayIndexOutOfBoundsException: 0
at ReverseFile.main(ReverseFile.java:36)

最佳答案

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

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

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) {
}
}


}


}

关于java - 如何读取文件、反转顺序和反转顺序写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16138380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com