How to keep formatting while reading files - java

I'm trying to read a .java file into a JTextArea and no matter what method I use to read in the file the formatting is never preserved. The actual code is ok but the comments always get messed up. Here are my attempts.
//Scanner:
//reads an input file and displays it in the text area
public void readFileData(File file)
{
Scanner fileScanner = null;
try
{
fileScanner = new Scanner(file);
while(fileScanner.hasNextLine())
{
String line = fileScanner.nextLine();
//output is a JTextArea
output.append(line + newline);
}
}
catch(FileNotFoundException fnfe)
{
System.err.println(fnfe.getMessage());
}
}
//Scanner reading the full text at once:
//reads an input file and displays it in the text area
public void readFileData(File file)
{
Scanner fileScanner = null;
try
{
fileScanner = new Scanner(file);
fileScanner.useDelimiter("\\Z");
String fullText = fileScanner.next();
//print to text area
output.append(fullText + newline);
}
catch(FileNotFoundException fnfe)
{
System.err.println(fnfe.getMessage());
}
}
//BufferedReader:
//reads an input file and displays it in the text area
public void readFileData(File file)
{
//Scanner fileScanner = null;
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line = "";
while((line = reader.readLine()) != null)
{
output.append(line + newline);
}
}
Is there anyway to keep the formatting the same??
PS - Also posted at http://www.coderanch.com/t/539685/java/java/keep-formatting-while-reading-files#2448353
Hunter

Use the JTextArea.read(...) method.

It may be due the var newline being hardcoded as '\n' or something like that. Try defining newline as follows:
String newline=System.getProperty("line.separator");
This solution is more "general", but I would use camickr solution if working with a JTextArea

Related

How to remove old data from text file using user input in Java

I am trying to get a user input and see if it matches any sentence in a text file. If so I want to remove the sentence. I mean I have the searching implementation so far all I need is help removing the sentence and possibly rewrite to the text file. I am not familiar with Java. Any help would be appreciated.
public static void searchFile(String s) throws FileNotFoundException {
File file = new File("data.txt");
Scanner keyboard = new Scanner(System.in);
// String lines = keyboard.nextLine();
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile + "is found already");
System.out.println("would you like to rewrite new data?");
String go = keyboard.nextLine();
if (go.equals("yes")) {
// Here i want to remove old data in the file if the user types yes then rewrite new data to the file.
}
}
}
}
I think you can't read and write into file on the same time so, make one temporary file and write all data with replaced text into new file and then move that temp file to original file.
I have appended code bellow, hope this helps.
File f = new File("D:\\test.txt");
File f1 = new File("D:\\test.out");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String s = "test";
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while((line = br.readLine()) != null){
if(line.contains(s)){
System.out.println(line + " is found already");
System.out.println("would you like to rewrite new data?");
String go = input.readLine();
if(go.equals("yes")){
System.out.println("Enter new Text :");
String newText = input.readLine();
line = line.replace(s, newText);
}
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);

Unable to write to file Scanner try/catch Java

When I run this program it is meant to write to the text file, the text file is located in the same directory as my project folder.
try
{
Scanner inFile = new Scanner(new File ("details.txt"));
while(inFile.hasNext())
{
String line = inFile.nextLine(); //reads the line of text
Scanner del = new Scanner(line).useDelimiter("#"); //scanner class to delimit
String name = del.next();
String gender = del.next();
int age = del.nextInt();
double amount = del.nextDouble();
txaDisplay.append(name+"\t"+gender+"\t"+age+"\t"+amount+"\n");
del.close();
}
inFile.close();//end try
}
catch(FileNotFoundException f)
{
txaDisplay.append("File Not Found");
System.exit(0);}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new yest().setVisible(true);
}
});}
You need to actually write to the file. Here's an example I give to people who are new to file output. This uses the FileWriter output stream. Note Data here is an ArrayList.
public static void WriteFile(File file)
{
System.out.println("Writing to file");
//Use a FileWriter to output to file
FileWriter oFile = null;
try
{
oFile = new FileWriter(file, false); //Set to true if you don't want to overwrite existing contents in file
// Begin writing to file... line by line
for (String line : Data)
oFile.write(line + System.getProperty("line.separator")); //Since notepad doesn't display newline characters (\n) use this
//If using another text document viewer then just use + "\n"
//Flush and close output stream
oFile.flush();
oFile.close();
} catch (IOException e)
{
// Handle it!
e.printStackTrace();
}
}

How to replace particular text in the txt file?

Here is my txt file look like.
admin 12345
funny 123
loop 12390
Hi guys. I am trying to replace particular text in my txt file. For example, I want to replace admin's 12345 with something else that I key in in my input2, it means I want to replace the String(pass) that I find out from txt file through scanner. If I use bufferedwritter, the whole content is going to rewrite..How o solve this problem. I am newbie of programming, kindly need you all help.
login.addActionListener(this);
public void actionPerformed(ActionEvent e) {
String inputUser = input1.getText();
String inputPass = input2.getText();
File loginf = new File("oop.txt");
try{
if(e.getSource()==login)
{
Scanner read = new Scanner(new File("oop.txt"));
boolean loginTry = true;
while(read.hasNext())
{
String user = read.next();
String pass = read.next();
if(inputUser.equals(user) && inputPass.equals(pass)){
loginTry=false;
break;
}
}
if(!loginTry)
{
JOptionPane.showMessageDialog(this,"Login Successful");
}
Here is a simple example on how to do what you want!
//Replace a line or word in a file
import java.io.*;
public class BTest
{
public static void main(String args[])
{
try
{
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
// replace a word in a file
//String newtext = oldtext.replaceAll("drink", "Love");
//To replace a line in a file
String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
OUTPUT
file.txt
I drink Java
I sleep Java
This is test string 1
This is test string 20000
I did both because the way your txt file is you have more than just a word, you have an ID number of some sorts right next to your users login information. So i would use change line!

Java code to remove initial lines of a file executing very slow

I have written java code to remove initial characters from a file with 200k records , the file is removing the initial characters but its reading the file line by line and removing the characters .The program is executing very slow . Any tweaks could be made to below code to execute it faster ?
The program is executing and writing the output to a file , but its very slow
import java.io.*;
import java.util.Scanner;
public class truncate {
public static void main(String [] args) {
// The name of the file to open.
String inputfile = "C:\\Program Files\\eclipse\\twfiles.txt";
String outputfile = "C:\\Program Files\\eclipse\\rename.txt";
// This will reference one line at a time
String line = "";
int number_of_char_to_erased =19;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(inputfile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
File input = new File(inputfile);
Scanner scan = new Scanner(input);
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while (scan.hasNext()) {
line = scan.nextLine();
line = line.substring(number_of_char_to_erased);
print.println(line);
}
scan.close();
print.close();
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
inputfile + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ inputfile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
What appears to be the issue here is that you just created a buffered reader to read the file. Then, it reads the first line of the file. Then, you create a Scanner to read ALL the lines in the file, omitting certain characters. Then your BufferedReader reads the next line in the file. And the process repeats itself. So all you have to do is this:
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while((line = bufferedReader.readLine()) != null) {
print.println(line.substring(number_of_char_to_erased);
}
print.close();
This should much faster. Basically, since you've already allocated line to the read line from the file, you can simply print out that line, minus the number of chars, to the output file. The entire for loop with scanner was entirely unnecessary, and closing and opening the print stream for each line was also unnecessary.
EDIT: Removed the println statement since it would slow it down a bit.
Try this (Scanner and Println removed, output file refactored outside the loop):
import java.io.*;
public class truncate {
public static void main(String [] args) {
// The name of the file to open.
String inputfile = "C:\\Program Files\\eclipse\\twfiles.txt";
String outputfile = "C:\\Program Files\\eclipse\\rename.txt";
// This will reference one line at a time
String line = "";
int number_of_char_to_erased =19;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputfile);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
File output = new File(outputfile);
PrintStream print = new PrintStream(output);
while((line = bufferedReader.readLine()) != null) {
String trimmedLine = line.substring(number_of_char_to_erased);
print.println(trimmedLine);
}
// Always close files.
bufferedReader.close();
print.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
inputfile + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ inputfile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}

Read last line from a file

So I am trying to read a file in Java. It works fine, unless the last line is empty, in which case it gets ignored; but I need to read this empty line too.
Here is my code:
try
{
BufferedReader in = new BufferedReader(new FileReader("filename.txt"));
String Line;
while((Line = in.readLine()) != null)
{
System.out.println("L| " + Line);
}
}
catch(Exception e){e.printStackTrace();}
}
first use scanner class...as they are hum easier to use....and then store each line in a list and then get the last line..here is the code:
public void readLast()throws IOException{
FileReader file=new FileReader("E:\\Testing.txt"); //address of the file
List<String> Lines=new ArrayList<>(); //to store all lines
Scanner sc=new Scanner(file);
while(sc.hasNextLine()){ //checking for the presence of next Line
Lines.add(sc.nextLine()); //reading and storing all lines
}
sc.close(); //close the scanner
System.out.print(Lines.get(Lines.size()-1)); //displaying last one..
}

Categories