Writing or modifying text files in java
Dear all,
I have the next text file:
goods: 5
bids: 4
% num, price, good, good, ..., good, #
0 2075 1 4 #
1 3000 1 2 3 4 #
2 520 3 #
3 3000 2 3 4 #
I have to modify or create the file above, using output data from one java program. For example, The output of my java program in the next execution is:
goods: 8
and price (0) changes from 2075 to 2078.
so, using this output data my java program should write (create or modify) the next text file with the changes:
goods: 8
bids: 4
% num, price, good, good, ..., good, #
0 2078 1 4 #
1 3000 1 2 3 4 #
2 520 3 #
3 3000 2 3 4 #
I have tried using: output.write( objetc );
but it doesn't work as I need :( .
Somebody can help me or give me some idea?
Thanks,
Andrea
This is the code:
File testFile = new File("D:\\result1.txt");
setContents(testFile, " bla bla bla (few characters) ");
static public void setContents(File aFile, String aContents)
throws FileNotFoundException, IOException {
try {
//use buffering
output = new BufferedWriter( new FileWriter(aFile) );
output.write( aContents );
finally {
//flush and close both "output" and its underlying FileWriter
if (output != null) output.close();
I mean, this code dont work because it let me write few characters only. I need to write the whole file:
goods: 8
bids: 4
% num, price, good, good, ..., good, #
0 2078 1 4 #
1 3000 1 2 3 4 #
2 520 3 #
3 3000 2 3 4 #
with the special characters as (#).
Sorry, if it post is not clear.
Thanks.
Similar Messages
-
How to read some records from a text file into java(not all records)
hello,
how to read text files into java. i need only few records from the text file not all records at a time.
If any one knows plz reply me
my id is [email protected]this snipet reads a text file line by line from line 1 to 3
try {
FileReader fr = new FileReader(directory);
BufferedReader br = new BufferedReader(fr);
int counter = 0;
while ((dbconn = br.readLine()) != null) {
switch(counter){
case 0:
status = dbconn;
break;
case 1:
userName = dbconn;
break;
case 2:
apword = dbconn;
break;
counter++;
br.close();
}catch(IOException e){
} -
How to print a text file using Java
How can I print a text file using Java without converting the output to an image format. Is there anyway I can send the characters in the text file as it is for a print job? I did get a listing doing this ... but that converted the text to an image format before printing....
THanks,.Hi I had to write a print api from scratch, and I did not convert the output to image. Go and read up on the following code. I know there is a Tutorial on Sun about the differant sections of the snippet.
private void printReport()
Frame tempFrame = new Frame(getName());
PrintJob printerJob = Toolkit.getDefaultToolkit().getPrintJob(tempFrame, "Liesltext", null);
Graphics g = printerJob.getGraphics();
//I wrote the method below for calculations
printBasics(g);
g.dispose();
printerJob.end();
}This alone wont print it you have to do all the calculations in the printBasics method. And as I said I wrote this from scratch and all I did was research first the tutorial and the white papers
Ciao -
How to get the source code of an HTML page in Text file Through java?
How to get the source code of an HTML page in Text file Through java?
I am coding an application.one module of that application is given below:
The first part of the application is to connect our application to the existing HTML form.
This module would make a connection with the HTML page. The HTML page contains the coding for the Form with various elements. The form may be a simple form with one or two fields or a complex one like the form for registering for a new Bank Account or new email account.
The module will first connect through the HTML page and will fetch the HTML code into a Text File so that the code can be further processed.
Could any body provide coding hint for thatYou're welcome. How about awarding them duke stars?
edit: cheers! -
How to replace a line ina text file using java?
Hi ALL,
Does anybody know how to replace a line in a text file uisng java.use this thing:
http://doesthatevencompile.com/current-projects/code-sniplets/ASCIIFile.htm
open the file,
read its contents, replace the text you need in the contents, set the contents back into the file.
it takes care of the IO for you. -
How to convert a HTML files into a text file using Java
Hi guys...!
I was wondering if there is a way to convert a HTML file into a text file using java programing language. Likewise I would also like to know if there is a way to convert any type of file (excel, power point, and word) into text using java.
By the way, I really appreciated the help that you guys gave me on my previous topic on how to extract tests from a pdf file.
Thank you....HTML files are already text files. What do you mean you want to convert them?
I think if you search the web, you can find things for converting those MS Office files to text (or extracting text from them, as I assume you mean). -
How to read a text file using Java
Guys,
Good day!
Please help me how to read a text file using Java and create/convert that text file into XML.
Thanks and God Bless.
Regards,
I-Talkpublic void fileRead(){
File aFile =new File("myFile.txt");
BufferedReader input = null;
try {
input = new BufferedReader( new FileReader(aFile) );
String line = null;
while (( line = input.readLine()) != null){
catch (FileNotFoundException ex) {
ex.printStackTrace();
catch (IOException ex){
ex.printStackTrace();
}This code is to read a text file. But there is no such thing that will convert your text file to xml file. You have to have a defined XML format. Then you can read your data from text files and insert them inside your xml text. Or you may like to read xml tags from text files and insert your own data. The file format of .txt and .xml is far too different.
cheers
Mohammed Jubaer Arif. -
Read Text file using Java Script
Hi,
I am trying to read a text file using Java Script within the webroot of MII as .HTML file. I have provided the path as below but where I am not able to open the file. Any clue to provide the relative path or any changes required on the below path ?
var FileOpener = new ActiveXObject("Scripting.FileSystemObject");
var FilePointer = FileOpener.OpenTextFile("E:\\usr\\sap\\MID\\J00\\j2ee\\cluster\\apps\\sap.com\\xapps~xmii~ear\\servlet_jsp\\XMII\\root\\CM\\OCTAL\\TestTV\\Test.txt", 1, true);
FileContents = FilePointer.ReadAll(); // we can use FilePointer.ReadAll() to read all the lines
The Error Log shows as :
Path not found
Regards,
MohamedHi Mohamed,
I tried above code after importing JQuery Library through script Tag. It worked for me . Pls check.
Note : You can place Jquery1.xx.xx.js file in the same folder where you saved this IRPT/HTML file.
<HTML>
<HEAD>
<TITLE>Your Title Here</TITLE>
<SCRIPT type="text/javascript" src="jquery-1.9.1.js"></SCRIPT>
<script language="javascript">
function Read()
$.get( "http://ldcimfb.wdf.sap.corp:50100/XMII/CM/Regression_15.0/CrossTab.txt", function( data ) {
$(".result").html(data);
alert(data);
// The file content is available in this variable "data"
</script>
</HEAD>
<BODY onLoad="Read()">
</BODY>
</HTML> -
Writing image to wbmp file in java
I am having problem writing images to wbmp files by java using the javax.imageio.* class. Though wbmp is present in the list given by writer format names.
String[] writers = ImageIO.getWriterFormatNames();
System.out.println("Can write to -");
for ( String s : writers)
System.out.println(s);
}but my code to convert an image format is not working for wbmp files
File in=new File("star.png");
File out=new File("def.wbmp");
File out1=new File("def.jpg");
BufferedImage image;
try {
image = ImageIO.read(in);
ImageIO.write(image,"wbmp",out);
ImageIO.write(image,"jpg",out1);
} catch (IOException e) {}the jpeg file is created successfully but the wbmp file remains empty. can you tell me where the problem is. Or is there some alternative method for image conversion.import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class WirelessPrep {
private JPanel getContent(BufferedImage image) {
JPanel panel = new JPanel(new GridLayout(1,0));
panel.add(wrap(image));
panel.add(wrap(convert(image)));
return panel;
private BufferedImage convert(BufferedImage image) {
// Convert to BufferedImage.TYPE_BYTE_BINARY
BufferedImage binary = convert(image, BufferedImage.TYPE_BYTE_BINARY);
BufferedImage wbmp = null;
File file = new File("wirelessPrep.wbmp");
try {
ImageIO.write(binary, "wbmp", file);
wbmp = ImageIO.read(file);
} catch(IOException e) {
System.out.println("io error: " + e.getMessage());
return wbmp;
private BufferedImage convert(BufferedImage src, int type) {
int w = src.getWidth();
int h = src.getHeight();
BufferedImage dst = new BufferedImage(w, h, type);
Graphics2D g2 = dst.createGraphics();
g2.drawImage(src, 0, 0, null);
g2.dispose();
return dst;
private JLabel wrap(BufferedImage image) {
ImageIcon icon = new ImageIcon(image);
JLabel label = new JLabel(icon, JLabel.CENTER);
return label;
public static void main(String[] args) throws IOException {
String path = "images/bison.jpg";
BufferedImage image = ImageIO.read(new File(path));
JPanel panel = new WirelessPrep().getContent(image);
JOptionPane.showMessageDialog(null, panel, "", -1);
} -
Changing HTML to text file using java
Hi,
I am doing a project in which i have to read news articles from websites. I have tried XML but for that i need to know which tag has the article in it. Since i have to read from various websites so each site used different tags for different informations.
Is there anyway that i can change an HTML file into a text file using java. Maybe some command that removes all the HTML tags and gives just the information. Is there anything else that anyone would like to recommend?
Thanx
yafisMaybe something like this:
import java.io.*;
import java.net.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
class GetHTMLText
public static void main(String[] args)
throws Exception
EditorKit kit = new HTMLEditorKit();
Document doc = kit.createDefaultDocument();
// The Document class does not yet handle charset's properly.
doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
// Create a reader on the HTML content.
Reader rd = getReader(args[0]);
// Parse the HTML.
kit.read(rd, doc, 0);
// The HTML text is now stored in the document
System.out.println( doc.getText(0, doc.getLength()) );
// Returns a reader on the HTML data. If 'uri' begins
// with "http:", it's treated as a URL; otherwise,
// it's assumed to be a local filename.
static Reader getReader(String uri)
throws IOException
// Retrieve from Internet.
if (uri.startsWith("http:"))
URLConnection conn = new URL(uri).openConnection();
return new InputStreamReader(conn.getInputStream());
// Retrieve from file.
else
return new FileReader(uri);
} -
How to edit/modify a line of a text file using java io
Hi every body
I am new 2 java
I am struck in editing a text file that ends with .dat
I successfully added,viewed data of the *.dat file.
but,I cannt edit,delete the lines that i need to do randomly.
Here is the code i have written.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class ReadWriteFile {
String id=null;
String name=null;
String dept=null;
String doj=null;
String adrss=null;
public void WriteFile(String Id,String Name,String Dept,String Doj,String Adrss) throws IOException{
File f=new File("TraineeDetails.dat");
if(!f.exists()){
f.createNewFile();
BufferedWriter bw=new BufferedWriter(new FileWriter("TraineeDetails.dat",true));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Id : ");
Id=br.readLine();
System.out.print("Enter name : ");
Name=br.readLine();
System.out.print("Enter dept : ");
Dept=br.readLine();
System.out.print("Enter doj : ");
Doj=br.readLine();
System.out.print("Enter adrss : ");
Adrss=br.readLine();
bw.write(Id+"::"+Name+"::"+Dept+"::"+Doj+"::"+Adrss+":END:");
bw.flush();
bw.newLine();
bw.close();
public static void main(String[] args) throws IOException {
ReadWriteFile rwf=new ReadWriteFile();
String TID = null;
String TADRSS = null;
String TDOJ = null;
String TNAME = null;
String TDEPT = null;
rwf.ReadFile(TID,TNAME,TDEPT,TDOJ,TADRSS);
public void ReadFile(String Id1,String Name1,String Dept1,String Doj1,String Adrss1) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("TraineeDetails.dat"));
String s;
while((s = br.readLine())!= null)
// Create string tokenizer
StringTokenizer st =new StringTokenizer(s, "::");
System.out.println("----------------------------------------------");
System.out.println("| Trainee Id: "+st.nextToken() +"|");
System.out.println("| Trainee Name: "+st.nextToken() +"|");
System.out.println("| Trainee Department:"+st.nextToken() +"|");
System.out.println("| Date of Joining: "+st.nextToken() +"|");
System.out.println("| Trainee Address: "+st.nextToken() +"|\n");
System.out.println("----------------------------------------------");
// Close file reader
br.close();
} and here is the data i have written
Trainee.dat*
111::jain::roads::2-2008::Blore:END:
123::tim::service::1-2000::delhi:END:
444::faru::civil::3-2200::sanapur:END:
555::niv::cse::10-2000::gnagar:END:
999::linda::mech::6-2001::tnagar:END:
258::yansi::geo::8-2002::rtnagar:END:
656::hari::garrage::3-1000::uttarahalli:END:
888::muni::hr::5-2009::ernakulam:END:
007::bond::spy::2-1972::america:END:
0123::landy::games::6-2003::hdp:END:
678::maddy::pumbing::4-1999::dispur:END:kalanidhi2u wrote:
I want to randomly access the file
But i cannt access itmake it RandomAccessFile... RandomAccessFile
I edited it
but i cannt edit the file by using itBoth of these are contradictory. -
hello!
i am creating an Applet game and I would like to create Rankings.
So, i need to take data from java and transfer them into HTML. At my
university's book says that everytime we open a file to write in it, if there are
already data, Java removes them and then writes the new ones. But I want
a static file where Java can write the updated rankings and HTML can take
them and use them in site. Is there any way to achive that guys?
If i wasn't clear, i just want a way to make Java not to delete any data in a file
everytime it needs to write something in it!
thanks alot!hello!
i am creating an Applet game and I would like to
create Rankings.
So, i need to take data from java and transfer them
into HTML. At my
university's book says that everytime we open a file
to write in it, if there are
already data, Java removes them and then writes the
new ones. But I want
a static file where Java can write the updated
rankings and HTML can take
them and use them in site. Is there any way to achive
that guys?
If i wasn't clear, i just want a way to make Java not
to delete any data in a file
everytime it needs to write something in it!
thanks alot!There are a number of problems here.
First of all you can always append to a file, but that's not actually what you want to do.
Second you can read the whole file in, find the values you want, change them and write the whole file back. This is more of what you want to do but HTML is not the best choice for doing this.
But the most fundamental problem is that you do not write to files of any kind in an Applet. -
Fill a text file from java code
Hello,
I've written a java code to insert some informations in a database and
I also want to save the same informations in text files (.txt).
Thanks you for your suggestions or your advice of a tutorial that can help me to perform successfully this task.
J.S.Writing to a file is pretty easy in Java. A simple way is to use the PrintStream class.import java.io.*;
public class MyClass {
public static void main(String[] arg) throws IOException {
PrintStream ps=new PrintStream(new FileOutputStream(new File("someTextFile.txt")));
//now use println(String) to write lines of text to the file
ps.println("This is a line in the file");
//always close the PrintStream when finished
ps.close();
}Alternatively, for a good tutorial, click the 'Tutorials' link in the left column on this page. -
Trying to write data to a text file using java.io.File
I am trying to create a text file and write data to it by using java.io.File and . I am using JDeveloper 10.1.3.2.0. When I try run the program I get a java.lang.NullPointerException error. Here is the snippet of code that I believe is calling the class that's causing the problem:
String fpath = "/test.html";
FileOutputStream out = new FileOutputStream(fpath);
PrintStream pout = new PrintStream(out);
Do I need to add additional locations for source files or am I doing something wrong? Any suggestions would be appreciated.
Thank you.Hi dhartle,
May be that can help:
* Class assuming handling logs and connections to the Oracle database
* @author Fabre tristan
* @version 1.0 03/12/07
public class Log {
private String fileName;
* Constructor for the log
public Log(String name) {
fileName = name;
* Write a new line into a log from the line passed as parameter and the system date
* @param line The line to write into the log
public void lineWriter(String line) {
try {
FileWriter f = new FileWriter(fileName, true);
BufferedWriter bf = new BufferedWriter(f);
Calendar c = Calendar.getInstance();
Date now = c.getTime();
String dateLog =
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM,
Locale.FRANCE).format(now);
bf.write("[" + dateLog + "] :" + line);
bf.newLine();
bf.close();
} catch (IOException e) {
System.out.println(e.getMessage());
* Write a new line into a log from the line passed as parameter,
* an header and the system date
* @param header The header to write into the log
* @param info The line to write into the log
public void lineWriter(String header, String info) {
lineWriter(header + " > " + info);
* Write a new long number as line into a log from the line
* passed as parameter, an header and the system date
* @param header The header to write into the log
* @param info The line to write into the log
public void lineWriter(String header, Long info) {
lineWriter(header + " > " + info);
* Enable to create folders needed to correspond with the path proposed
* @param location The path into which writing the log
* @param name The name for the new log
* @return Log Return a new log corresponding to the proposed location
public static Log myLogCreation(String location, String name) {
boolean exists = (new File(location)).exists();
if (!exists) {
(new File(location)).mkdirs();
Log myLog = new Log(location + name);
return myLog;
* Enable to create the connection to the DB
* @return Connection Return a new connection to the Oracle database
public static Connection oracleConnectionCreation() throws Exception {
// Register the Oracle JDBC driver
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
//connecting to the DB
Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@myComputerIP:1521:myDB","user", "password");
return conn;
* This main is used for testing purposes
public static void main(String[] args) {
Log myLog =
Log.myLogCreation("c:/Migration Logs/", "Test_LinksToMethod.log");
String directory = "E:\\Blob\\Enalapril_LC-MS%MS_MS%MS_Solid Phase Extraction_Plasma_Enalaprilat_ERROR_BLOB_test";
myLog.lineWriter(directory);
System.out.println(directory);
[pre]
This class contained some other functions i've deleted, but i think it still works.
That enables to create a log (.txt file) that you can fill line by line.
Each line start by the current system date. This class was used in swing application, but could work in a web app.
Regards,
Tif -
Sorting Names in a text file using java program
h1. Deleting numbers in a text file, sorting the names and writing in to a new file
h2. Sample data
=================
71234 RAJA
89763 KING
89877 QUEEN
==================
h2. Java Program
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
class Sortnames {
public static void main(String args[]) {
try {
ArrayList storeWordList = new ArrayList();
ArrayList storeWordList2 = new ArrayList();
int i;
char c;
String inputfile = "names_konda.txt";
String tempfile = "newdatafile.txt";
String outputfile = "sortedoutput.txt";
StringBuffer strBuff=null;
Writer output = null;
File file =null;
Writer sortedoutput = null;
boolean select =false;
//*********************************************** Reading data from Input file
FileInputStream fstream = new FileInputStream(inputfile);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
storeWordList.add(strLine);
//Close the input stream
in.close();
//*********************************************** Adding only alphabets to buffer and writing to file
file= new File(tempfile);
output = new BufferedWriter(new FileWriter(file));
strBuff = new StringBuffer();
for (Iterator iter = storeWordList.iterator(); iter.hasNext();) {
String s = (String) iter.next();
//System.out.println("String "+s);
for (i = 0; i < s.length() ; i++)
c = s.charAt(i);
if (Character.isLetter(c)) {
strBuff.append(c);
strBuff.append("\n");
String myout = strBuff.toString();
output.write(myout);
output.close();
//============================================== Reading the created file,Sorting and placing in Collections
FileInputStream fstream2 = new FileInputStream(tempfile);
// Get the object of DataInputStream
DataInputStream in2 = new DataInputStream(fstream2);
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String strLine2;
//Read File Line By Line
while ((strLine2 = br2.readLine()) != null) {
storeWordList2.add(strLine2);
Collections.sort(storeWordList2);
//===================================================
File sortedfile = new File(outputfile);
sortedoutput = new BufferedWriter(new FileWriter(sortedfile));
for(int m=0; m<storeWordList2.size(); m++)
if (storeWordList2.get(m).toString().trim().length() > 0)
sortedoutput.write(storeWordList2.get(m).toString());
sortedoutput.write("\n");
sortedoutput.close();
System.out.println("Names Sorted SUCCESFULLY");
br.close();
br2.close();
in.close();
fstream.close();
fstream2.close();
///==========================================
File f1 = new File(tempfile);
boolean success = f1.delete();
if (!success){
System.out.println("failed deletion ");
System.exit(0);
}else{
System.out.println("deleted");
// ==========================================
} catch (Exception e) {//Catch exception if any
System.out.println("Error: " + e);
h2. Thanks and regards
h1. BalaNagaRaju.M
h1. [email protected]Do you have a question? Also see the sticky welcome post on how to post formatted code.
Maybe you are looking for
-
The error box is entitled firefox.exe - Unable To Locate Component. It suggests re-installing may fix the problem but I've un-installed and re-installed firefox a number of times and no change.
-
ITouch 2G upgrade to iOS 4.2
I have the 2nd generation iTouch running IOS 3.1.3 and not able to find a way to upgrade it to IOS 4.2. I have tried iTunes "check for updates" but it keeps saying that there are no updates available. Model: MB376C. Without upgrading, there are
-
ok, this is making me nuts. i'm trying to upgrade the firmware for my muvo n200 and i've followed the instructions below to the T. everything works fine, until i get to #8. i run the firmware update program and i get an error message, put your player
-
How do I create a Podcast?
I know you need a microphone, but what else do you need to do?
-
Problems printing out a trusted certificate
When trying to print a trusted certificate (generated with OpenSSL) exported from my keystore, I get the following exception: Exception occurred during event dispatching: java.lang.IllegalArgumentException: DER Value conversion Trying to print this c