I have a java program that saves a text file and then outputs it contents in a dialog.
When I run the program inside my IDE (BlueJ) the display is as follows:
As you can see in the dialog the line "1º) Mónica" appears correctly.
But when I run the same program outside the IDE the "Mónica" doesn't appear right, as you can see in the picture:
How can I fix this to always display the right output?
this is the code that reads the text file to a string
public String recordesString()
{
Premios premios = new Premios();
File recordes = new File("recordes.txt");
if(!recordes.exists()) {
if(!client.isConnected())
openFTPSession();
downloadRecordes(); // this downloads the recordes.txt file
}
Scanner s = null;
try {
s = new Scanner(recordes);
} catch (Exception e) {
e.printStackTrace();
}
String string = "";
String linha = null;
for(int i = 1; s.hasNext(); i++) {
linha = s.nextLine();
String palavra[] = linha.split(" ",2);
string += i+"º) "+palavra[1] +" "+ premios.getPremio(Integer.parseInt(palavra[0]))+"\n";
}
s.close();
try {
Files.deleteIfExists(Paths.get(ficRecordes));
} catch (Exception e) {
e.printStackTrace();
}
return string;
}
Scanner reads the file using the underlying platform's default charset.
See http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)
I'd expect the file is encoded in UTF-8 and when you run outside the IDE, the default charset is ISO-latin-1 or so. If you specify the file's encoding when creating the scanner, the results will be predictable.
s = new Scanner(recordes, "UTF-8");
Related
I am working on the project. For my purpose, I need to use them that find the median of medians.
At my point, I need to see the read
I also created the input.txt like that below
3 7
1 4 5 7 9 11 13
Below the snippet, I created the variable for the readpath.
// need the variable of filename to read
private static final String INPUT_FILE_PATH = "input.txt";
So, then I appended the code that needs to read the numerical integers in the input.txt in the main function as known below
public static void main(String args[]){
// read the input file
// TODO need to fix this readpath that gets the bad input
// ! ASAP
Path inputPath = Paths.get(INPUT_FILE_PATH);
Charset charset = Charset.forName("UTF-8");
List<String> fileLines = new ArrayList<>(0);
try {
fileLines = Files.readAllLines(inputPath, charset);
} catch (IOException ex) {
System.err.println("Error reading file: " + ex.getMessage());
System.exit(1);
}
int read_line = 0;
try {
read_line = Integer.parseInt(fileLines.get(0));
} catch (NumberFormatException ex) {
System.err.println("bad file input");
System.exit(1);
}
System.out.println("reading... " + read_line);
// end of reading the filename operation
}
As a result, this code suppose to work. I get the output that is bad file input. I do not understand why it gets bad file. By the way, I put all files together in the same directory.
int read_line = 0;
int read_line2 = 0;
try {
String[] words = fileLines.get(0).split("\\s+"); // Split on whitespace.
read_line = Integer.parseInt(words[0]);
read_line2 = Integer.parseInt(words[1]);
} catch (NumberFormatException ex) {
System.err.println("bad file input - not a number; " + e.getMessage());
System.exit(1);
}
The line contains two numbers, and results in a NumberFormatException.
I want to read a text file , change some text then output to a text file. I'd open this file in notepad
New to Java - This has been rehashed and posted in different way throughout the forum. They always seem to say your missing the /n in the string - I thought I did this in the below code.
The part that is confusing to me is it displays in my terminal correctly when I use the showfile method.
I assume its the way I'm writing the file. I'd like to continue to use my method instead of the String variable
Original file contains text
Bob
Red
Door
I use this to read the text file and input it in a string.
public void readFile(String fileName)
{
fileText = "";
try
{
Scanner file = new Scanner(new File(fileName));
while (file.hasNextLine())
{
String line = file.nextLine();
fileText += line +"\n";
}
file.close();
}
catch (Exception e)
{
System.out.println(e);
}
I use a method to swap all "R"s to "B"s.
I use showFile method and it displays in my terminal correctly
This shows correctly
Bob
Bed
Door
public String showFile()
{
return fileText;
}
But then I try output the string to a file using.
try {
File file = new File("test1.txt");
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(startupModified.showFile());
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
It keeps my spacing but I loose my line breaks
Displays:
Bob
Bed
Door
This is the constructor class for startupModified
public StartUpFile(String fileName)
{
readFile(fileName);
}
functions correctly now
changed fileText += line +"\n";
to fileText += line +"\r\n";
I assumed it was the writer because it displayed correctly in the terminal.
Thank you
I have a problem and don't know what to do. This method is supposed to read all the text in a .txt document. My problem is when the document contains more then one line of text and the program only read the last line. The program don't need to worry about signs like . , : or spaces, but it have to read all the letters. Can anybody help me?
example text
hello my name is
(returns the right result)
hello my
name is
(returns only name is)
private Scanner x;
String readFile(String fileName)
{
try {
x = new Scanner (new File(fileName + (".txt")));
}
catch (Exception e) {
System.out.println("cant open file");
}
while (x.hasNext()) {
read = x.next();
}
return read;
}
It's because when you use read = x.next(), the string in the read object is always being replaced by the text in the next line of the file. Use read += x.next() or read = read.concat(x.next()); instead.
You replace every read with every read(). Also, you didn't close() your Scanner. I would use a try-with-resources and something like,
String readFile(String fileName)
{
String read = "";
try (Scanner x = new Scanner (new File(fileName + (".txt")));) {
while (x.hasNextLine()) {
read += x.nextLine() + System.lineSeparator(); // <-- +=
}
} catch (Exception e) {
System.out.println("cant open file");
}
return read;
}
I'm trying to read a moderately sized txt file (65,00 words) into a String, then a string array. The bufferedreader throws the "could not read file" catch. When I clear it, a small part of the contents of the text file is shown in the system.out. I do not get the error with smaller text files. I'm a beginner and I'm having a lot of trouble trying to narrow down the issue.
Why isn't the BufferedReader ingesting the entire file? And why is the "could not read file" error being thrown?
public class Main {
public static void main(String[] args) {
final Guid Main = new Guid(); //creates instance of Guid
Main.mergeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
merge();
}
});
}
static void merge()
{
//read file and turn into string
String pathone = open(Guid.PathOne);
System.out.print(pathone);
//parse and format
//String[] oneArray = pathone.replace("\n"," ").split(" ");
//get pathtwo text
//String pathtwo = open(Guid.PathTwo);
//parse and format
//load into array
//compare array entries
//add new array entry
//sort array
//write array to paththree file
//for(int i=0; i<oneArray.length;i++)
//{
//System.out.println(oneArray[i]);
//}
}
public static String open(JTextArea Path)
{
String record = null;
FileReader frFile = null;
try {
frFile = new FileReader(Path.getText());//gets file from Path
BufferedReader brFile = new BufferedReader(frFile);//creates buffered reader
record = brFile.readLine() + "\n"; //gets contents of file and puts it into a string
brFile.mark(0);
while (brFile.read() != -1) //loop to read the rest of the text file
{
brFile.reset();
record = record + brFile.readLine() + "\n";
brFile.mark(0);
}
}
catch (FileNotFoundException e) //catch path is in error
{
JFrame frame = null;
JOptionPane.showMessageDialog(frame, "Could not find file.");
}
catch (IOException e) //catch if file cannot be read
{
JFrame frame = null;
JOptionPane.showMessageDialog(frame, "Could not read file.");
}
try { //closes file
frFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return record;
}
}
Do in this way. Remove reset() and mark() methods if you want to read the entire file.
StringBuilder record = new StringBuilder();
BufferedReader brFile = new BufferedReader(frFile);
String line = null;
while ((line = brFile.readLine()) != null) {
record.append(line).append("\n");
}
Note:
Don't forget to close the stream.
Use finally block to close the stream
Use StringBuilder or StringBuffer to append the string.
Use System.getProperty("line.separator") to get the system specific line separator
Have a look at Java7 try-with-resources Statement advantage
readLine will read the first line of your document.
Try with it (not tested):
String lineReaded;
while ((lineReaded=brFile.readLine())!=null)
{
record +=linereaded+"\n";
}
Niko
You might like to use Files.readAllLines
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I've been trying to rename files and folders in a given folder by finding and replacing a substring in their name. Also, the name of file is contained in their contents also. I need to replace it to the new name.
For Example:
Change "XXX" to "KKK" in all the files and folder names and also in file contents:
Original file name: 0001_XXX_YYY_ZZZ.txt
New file name: 0001_KKK_YYY_ZZZ.txt
Following is the code that I'm using.
When I run the following code without calling the function replaceText(), its renaming the file and folder. But, when I try to change the text of file and then rename the file and folder; contents of file is changed but renaming of both file and folder fails.
Please help.
public class FindReplaceAnywhere {
public static void main(String[] args) {
String find = "XXX";
String replace = "KKK";
String baseLoc = "D:\\0001_XXX_YYY_ZZZ";
FindReplaceAnywhere obj = new FindReplaceAnywhere();
File baseLocObj = new File(baseLoc);
LinkedList<File> baseFolderList = new LinkedList<File>();
// Add base folder object to list
baseFolderList.add(baseLocObj);
// Get list of files in the folder
for(File file: baseLocObj.listFiles()) {
baseFolderList.add(file);
}
// Rename the files, folders & contents of files
obj.rename(baseFolderList, find, replace);
}
public void rename(LinkedList<File> fileList, String find, String replace) {
String tempStr = null;
int beginIndex = 0;
int endIndex = 0;
File tempFile;
System.out.println(">>> Batch Rename Process Begins >>>\n");
for(File aFile:fileList) {
// If Object is File, change the text also
if(aFile.isFile()) {
replaceText(aFile,find,replace);
}
}
for(File aFile: fileList) {
System.out.println("Processing>>>");
System.out.println(aFile.getPath());
if(aFile.getName().contains(find)) {
// Get the name of File object
beginIndex = aFile.getPath().length() - aFile.getName().length();
endIndex = aFile.getPath().length();
tempStr = aFile.getPath().substring(beginIndex, endIndex);
tempStr = tempStr.replace(find, replace);
}
else {
System.out.println("Error: Pattern not found\n");
continue;
}
tempFile = new File(aFile.getParentFile(),tempStr);
boolean success = aFile.renameTo(tempFile);
if(success) {
System.out.println("File Renamed To: "+tempFile.getName());
}
else {
System.out.println("Error: Rename Failed\nPossible Cause: File is open in another application");
}
System.out.println("");
}
}
/**
* Replace the text of file if it contains filename
*/
public void replaceText(File file, String find, String replace) {
String fullText = "";
String line = "";
String fileName = "";
String replaceName = "";
BufferedReader in;
BufferedWriter out;
// Read the file contents
try {
in = new BufferedReader(new FileReader(file));
while((line = in.readLine()) != null) {
fullText+=line+"\n";
}
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
// Replace the text of file
fileName = file.getName().substring(0, file.getName().indexOf("."));
replaceName = fileName.replace(find, replace);
fullText = fullText.replace(fileName, replaceName);
// Write the replaced text to file
try {
out = new BufferedWriter(new FileWriter(file));
out.write(fullText);
out.close();
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
It doesn't look like you're closing your input (in) file after reading it, which will hold that file open - Under *nix a rename should still work, but it will fail under Windows:
Use a finally block to ensure that the resource is closed.. but only after you're assured that it was opened.
While I'm at it, please allow me to suggest another change to the code:
Move "declarations" to the the absolute last point in the code where they can be made.. avoid declaring early. In this case, both in and out are unnecessarily declared early. There are others; I'll leave that for you to work out.
So, for the input file:
// Read the file contents
try {
BufferedReader in = new BufferedReader(new FileReader(file));
// If you got this far, the file is open...
// use try/finally to ensure closure.
try {
while((line = in.readLine()) != null) {
fullText+=line+"\n";
}
}
finally {
in.close();
}
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
and for the output file:
// Write the replaced text to file
try {
BufferedWriter out = new BufferedWriter(new FileWriter(file));
try {
out.write(fullText);
}
finally {
out.close();
}
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}