在java中,如何将文本文件中所有字符的大小写更改为小写?
因此,如果文本文件的内容为FCCCC,则同一文本文件的输出应为FCCCC 我已经编写了以下代码在java中,如何将文本文件中所有字符的大小写更改为小写?,java,Java,因此,如果文本文件的内容为FCCCC,则同一文本文件的输出应为FCCCC 我已经编写了以下代码 import java.lang.*; import java.io.*; import java.io.FileWriter; import java.io.IOException; class A { public static void main(String args[]) throws IOException { try {
import java.lang.*;
import java.io.*;
import java.io.FileWriter;
import java.io.IOException;
class A
{
public static void main(String args[]) throws IOException
{
try
{
FileReader reader = new FileReader("doc1.txt");
FileWriter writer = new FileWriter("doc1.txt", true);
int character=' ';
char m;
while ((character = reader.read()) != -1)
{
m=Character.toLowerCase((char)character);
System.out.println(m);
writer.write(m);
}
reader.close();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
在上述代码中,如果文本文件的内容为FCCCC,则输出为FCCCCFCCC
代码中有什么错误?请尝试以下操作:
import java.io.*;
public class TextFile {
public static void main (String[] args) throws IOException {
File file1 = new File("intext.txt");
File file2 = new File("outtext.txt");
char CharCounter = 0;
BufferedReader in = (new BufferedReader(newFileReader(file1)));
PrintWriter out = (new PrintWriter(new FileWriter(file2)));
int ch;
while ((ch = in.read()) != -1){
if (Character.isUpperCase(ch)){
Character.toLowerCase(ch);
}
out.write(ch);
}
in.close();
out.close();
}
}
然后删除旧文本并重命名新文本。您的
编写器正在写入您的读取器正在读取的同一文本文件
尝试写入其他文本文件。您可以使用java.io.RandomAccessFile
。它允许您读取和写入文件,获取文件指针并设置文件指针。该方案:
public static void main(String args[]) throws IOException {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile("C:\\Untitled.txt", "rw");
long length = raf.length();
byte[] buffer = new byte[(int) length];
long pointer = 0;
while (raf.read(buffer) != -1) {
String upperCase = new String(buffer).toUpperCase();
raf.seek(pointer);
raf.writeBytes(upperCase);
pointer = raf.getFilePointer();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (raf != null)
raf.close();
}
}
raf.length()
返回文件中的字节数
raf.read(buffer)
读取buffer.length
进入buffer
数组的字节数
raf.seek(指针)代码>将文件指针设置为当前读取之前的位置
raf.getFilePointer()代码>在下次读取之前获取文件指针位置,以便能够从此位置开始写入。我搜索我的问题以解决我的问题,并查看您的代码。
这是我的代码,在控制台中给你你想要的
我希望你喜欢
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
public class WordCounter {
private static String Say;
public static void main(String[] args) throws FileNotFoundException {
File file = new File("Top250imdbMovies.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()){
String line = scanner.nextLine();
Say = line.toLowerCase();
System.out.println(Say);
}
}
}
那是sysout还是在文件中,你得到的是“fccccfccc”?因为我认为,你是在附加到文件中,这就是为什么?请尝试先清理文件内容,然后写入文件。确定首先读取文件中的所有内容,然后重新编写创建新的FileWriter对象时,构造函数中的布尔值决定它是否附加到文件而不是覆盖它。您应该将其设置为“false”,或者只使用“(File)”构造函数而不是“(File,boolean)”构造函数。为True,但我希望替换同一文本文件中的字符。如果要使用同一文件,可能需要查看以下问题的答案: